To implement the progress tracking in NestJS and PostgreSQL using TypeORM, the following steps can be taken:
- Define a database schema for storing user progress information. This schema should include fields for the user ID, the word ID, the user's progress status (unknown, learned, or learning), and any additional information needed to track progress for each word. For example:
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class UserWord {
@PrimaryGeneratedColumn()
id: number;
@Column()
userId: number;
@Column()
wordId: number;
@Column()
progress: string;
// additional fields for tracking progress can be added here
}
- Create a controller to handle CRUD operations for the user word progress data. This controller should include functions for creating a new user word progress record, updating an existing record, fetching progress data for a specific user and word, and fetching progress data for all words for a user.
import { Body, Controller, Get, Param, Post, Put } from '@nestjs/common';
import { UserWord } from './user-word.entity';
import { UserWordsService } from './user-words.service';
@Controller('user-words')
export class UserWordsController {
constructor(private readonly userWordsService: UserWordsService) {}
@Post()
async create(@Body() userWord: UserWord): Promise<UserWord> {
return this.userWordsService.create(userWord);
}
@Put(':id')
async update(
@Param('id') id: string,
@Body() userWord: UserWord,
): Promise<UserWord> {
return this.userWordsService.update(id, userWord);
}
@Get(':userId/:wordId')
async findOne(
@Param('userId') userId: string,
@Param('wordId') wordId: string,
): Promise<UserWord> {
return this.userWordsService.findOne(userId, wordId);
}
@Get(':userId')
async findAll(@Param('userId') userId: string): Promise<UserWord[]> {
return this.userWordsService.findAll(userId);
}
}
- Create a service to handle the business logic for the progress tracking system. This service should include functions for creating new progress records, updating existing progress records, fetching progress data for a specific user and word, and fetching progress data for all words for a user.
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserWord } from './user-word.entity';
@Injectable()
export class UserWordsService {
constructor(
@InjectRepository(UserWord)
private readonly userWordsRepository: Repository<UserWord>,
) {}
async create(userWord: UserWord): Promise<UserWord> {
const existingUserWord = await this.findOne(
userWord.userId.toString(),
userWord.wordId.toString(),
);
if (existingUserWord) {
userWord.id = existingUserWord.id;
userWord.progress = existingUserWord.progress;
}
return this.userWordsRepository.save(userWord);
}
async update(id: string, userWord: UserWord): Promise<UserWord> {
const existingUserWord = await this.userWordsRepository.findOne(id);
if (!existingUserWord) {
return null;
}
return this.userWordsRepository.save({ ...existingUserWord, ...userWord });
}
async findOne(userId: string, wordId: string): Promise<UserWord> {
return this.userWordsRepository.findOne({ userId, wordId });
}
async findAll(userId: string): Promise<UserWord[]> {
return this.userWordsRepository.find({ userId });
}
}
- Modify the game logic to use the progress tracking service for recording user progress. When the user selects an article for a French word, update the progress tracking record for that user and word accordingly:
import { Component } from '@angular/core';
import { UserWordService } from '../services/user-word.service';
interface FrenchWord {
text: string;
example: string;
gender: string;
article: string;
}
@Component({
selector: 'app-french-gender-game',
templateUrl: './french-gender-game.component.html',
styleUrls: ['./french-gender-game.component.css']
})
export class FrenchGenderGameComponent {
frenchWords: FrenchWord[];
currentWordIndex: number;
selectedArticle: string;
progressStatus: string;
constructor(private userWordsService: UserWordsService) {}
ngOnInit() {
// load list of French words and associated progress information for the current user
this.frenchWords = this.loadFrenchWords();
this.currentWordIndex = 0;
this.selectedArticle = '';
}
onSelectArticle(article: string) {
// update selected article and check for correctness
this.selectedArticle = article;
const currentWord = this.frenchWords[this.currentWordIndex];
if (this.selectedArticle === currentWord.article) {
currentWord.text = this.highlightWord(currentWord.text, 'green');
this.progressStatus = 'learned';
} else {
currentWord.text = this.highlightWord(currentWord.text, 'red');
this.progressStatus = 'learning';
}
// save user progress for the current word
this.userWordsService.saveProgress(currentWord.text, this.progressStatus);
// go to next word
this.currentWordIndex = (this.currentWordIndex + 1) % this.frenchWords.length;
this.selectedArticle = '';
}
loadFrenchWords(): FrenchWord[] {
// load French words and associated progress information for the current user from the server
// this can be done through a REST API call using the user ID
const userId = 123;
return [
{
text: 'chat',
example: 'Le chat est noir.',
gender: 'masculine',
article: 'LE'
},
{
text: 'maison',
example: 'Une maison en pierre.',
gender: 'feminine',
article: 'UNE'
},
{
text: 'vélo',
example: 'Un vélo rouge.',
gender: 'masculine',
article: 'UN'
},
// ... other French words
];
}
}
- Use the progress tracking API to fetch and display progress information for the user. This can be done using the user ID and the progress tracking controller's API endpoints.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class UserWordsService {
baseUrl = 'http://localhost:3000/user-words';
constructor(private http: HttpClient) {}
async saveProgress(word: string, progress: string) {
const userId = 123; // replace with the current user's ID
const existingUserWord = await this.getProgress(userId, word);
const userWord = {
userId,
wordId: word.hashCode(), // use the hash code of the word text as the unique word ID
progress: existingUserWord ? existingUserWord.progress : progress
};
return this.http.post(this.baseUrl, userWord).toPromise();
}
async getProgress(userId: number, word: string) {
const wordId = word.hashCode(); // use the hash code of the word text as the unique word ID
return this.http.get(`${this.baseUrl}/${userId}/${wordId}`).toPromise();
}
async getAllWordsProgress(userId: number) {
return this.http.get(`${this.baseUrl}/${userId}`).toPromise();
}
}
- Hash code implementation in the saveProgress function:
String.prototype.hashCode = function() {
let hash = 0;
if (this.length === 0) {
return hash;
}
for (let i = 0; i < this.length; i++) {
const char = this.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
By following these steps, you should be able to successfully implement progress tracking in NestJS and PostgreSQL.