Add seeding to users

This commit is contained in:
2026-03-06 09:08:00 +01:00
parent 6a25030d90
commit 432e27329c
3 changed files with 30 additions and 3 deletions

View File

@@ -2,7 +2,7 @@ node_modules
dist/*
!dist/csv/
dist/csv/*
!dist/csv/tournaments.csv
!dist/csv/*.csv
*.sqlite
_requests.http
request_logs.txt

View File

@@ -0,0 +1,2 @@
username, password
tikaiz, htlgkr
1 username password
2 tikaiz htlgkr

View File

@@ -1,18 +1,43 @@
import { User } from '../models/user';
import { Database } from 'sqlite3';
import * as argon2 from 'argon2';
import fs from "fs";
import path from "path";
export class UserService {
private csvFilename = 'csv/users.csv';
private db: Database;
constructor(db: Database) {
this.db = db;
this.db.serialize(() => {
this.db.run(`CREATE TABLE IF NOT EXISTS Users
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)`);
this.seedDb();
})
}
seedDb() {
fs.readFile(path.join(process.cwd(), "dist", this.csvFilename), 'utf-8', async (_, data) => {
const entries = data.split('\n');
entries.shift();
const lines = entries.filter(line => line.trim());
const statement = this.db.prepare(`INSERT INTO Users
(username, password)
VALUES (?, ?)`);
for (const line of lines) {
const parts = line.split(',');
const username = parts[0].trim();
const hash = await argon2.hash(parts[1].trim());
statement.run(username, hash);
console.log({ username, password: hash });
}
statement.finalize();
});
}
register(username: string, password: string): Promise<{ id: number; username: string }> {