moved to node
This commit is contained in:
10
.gitignore
vendored
10
.gitignore
vendored
@@ -1,7 +1,5 @@
|
|||||||
node_modules
|
node_modules/
|
||||||
frontend/dist
|
server/node_modules/
|
||||||
frontend/node_modules
|
frontend/node_modules/
|
||||||
.idea
|
frontend/dist/
|
||||||
.vim
|
|
||||||
config.json
|
config.json
|
||||||
pizza-collage
|
|
||||||
|
|||||||
8
server/.env
Normal file
8
server/.env
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
set -o allexport
|
||||||
|
DB_USER="stoccatre"
|
||||||
|
DB_HOST="localhost"
|
||||||
|
DB_PASS="password"
|
||||||
|
DB_PORT=3306
|
||||||
|
HOST="localhost"
|
||||||
|
PORT=8080
|
||||||
|
set +o allexport
|
||||||
2
server/.gitignore
vendored
Normal file
2
server/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
import Http = Deno.errors.Http;
|
|
||||||
import {JSONObject} from "./JSON.ts";
|
|
||||||
|
|
||||||
export type HttpMethod = "POST" | "GET" | "PUT" | "DELETE";
|
|
||||||
|
|
||||||
export type RouteDefinition = {
|
|
||||||
pattern: RegExp;
|
|
||||||
method?: HttpMethod;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default class StoccaTreRequest {
|
|
||||||
constructor(
|
|
||||||
public method: HttpMethod,
|
|
||||||
public route: string,
|
|
||||||
public body: JSONObject | null,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
match(route: RouteDefinition): RegExpExecArray | false {
|
|
||||||
const patternResult = route.pattern.exec(this.route);
|
|
||||||
if (route.method && route.method !== this.method) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return patternResult ?? false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import StoccaTreRequest from "./StoccaTreRequest.ts";
|
|
||||||
import { Result } from "./Result.ts";
|
|
||||||
import { JSONObject } from "./JSON.ts";
|
|
||||||
|
|
||||||
export default interface StoccaTreRequestHandler {
|
|
||||||
handleRequest(request: StoccaTreRequest): Promise<Result<JSONObject> | null>;
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import StoccaTreRequestHandler from "./StoccaTreRequestHandler.ts";
|
|
||||||
import StoccaTreRequest, { RouteDefinition } from "./StoccaTreRequest.ts";
|
|
||||||
import { Result, StoccaTreError } from "./Result.ts";
|
|
||||||
import { JSONObject } from "./JSON.ts";
|
|
||||||
import { StoccaTreDbConn } from "./database.ts";
|
|
||||||
|
|
||||||
export default class StoccaTreServer implements StoccaTreRequestHandler {
|
|
||||||
private db: StoccaTreDbConn;
|
|
||||||
private routes: {
|
|
||||||
routeDef: RouteDefinition;
|
|
||||||
handler: StoccaTreRequestHandler;
|
|
||||||
}[] = [];
|
|
||||||
|
|
||||||
constructor(dbConnection: StoccaTreDbConn) {
|
|
||||||
this.db = dbConnection;
|
|
||||||
}
|
|
||||||
|
|
||||||
addResource(route: RouteDefinition, handler: StoccaTreRequestHandler) {
|
|
||||||
this.routes.push({ routeDef: route, handler });
|
|
||||||
}
|
|
||||||
|
|
||||||
async handleRequest(request: StoccaTreRequest): Promise<Result<JSONObject>> {
|
|
||||||
let result: Result<JSONObject> | null = null;
|
|
||||||
for (const { routeDef, handler } of this.routes) {
|
|
||||||
if (request.match(routeDef)) {
|
|
||||||
result = await handler.handleRequest(request);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!result) {
|
|
||||||
return [new StoccaTreError(`Invalid route: ${request.route} with method ${request.method}.`, 400)];
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
const config = {
|
|
||||||
dbUsername: Deno.env.get("DB_USER") ?? "postgres",
|
|
||||||
dbHostname: Deno.env.get("DB_HOST") ?? "localhost",
|
|
||||||
dbPassword: Deno.env.get("DB_PASS") ?? "",
|
|
||||||
dbPort: Number(Deno.env.get("DB_PORT") ?? 5432),
|
|
||||||
hostname: Deno.env.get("HOST") ?? "localhost",
|
|
||||||
port: Number(Deno.env.get("PORT") ?? 8080),
|
|
||||||
};
|
|
||||||
|
|
||||||
console.log(`ENV:
|
|
||||||
db username: ${config.dbUsername}
|
|
||||||
db hostname: ${config.dbHostname}
|
|
||||||
db pass: ******
|
|
||||||
db port: ${config.dbPort}
|
|
||||||
server port: ${config.port}
|
|
||||||
server hostname: ${config.hostname}
|
|
||||||
`);
|
|
||||||
|
|
||||||
export default config;
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
import { Client } from "postgres";
|
|
||||||
import config from "./config.ts";
|
|
||||||
import { JSONObject } from "./JSON.ts";
|
|
||||||
import { Result, StoccaTreError } from "./Result.ts";
|
|
||||||
|
|
||||||
type Interpolable = number | string | bigint | null | boolean;
|
|
||||||
type UnionToIntersection<Union> =
|
|
||||||
(Union extends any ? (x: Union) => any : never) extends (x: infer Intersection) => any
|
|
||||||
? Intersection
|
|
||||||
: never;
|
|
||||||
type SQLWithArg<Arg> = Arg extends string ? `${string}$${Arg}${string}` : never;
|
|
||||||
type SQLWithArgs<Args extends Record<string, Interpolable>> = UnionToIntersection<SQLWithArg<keyof Args>>;
|
|
||||||
type ArgNamesInSQL<SQL extends string> =
|
|
||||||
SQL extends `${string}$${infer Arg1} ${infer SQLAfterArg1}`
|
|
||||||
? Arg1 extends `${infer Arg1NoTrailing}${";" | "," | "'" | "\"" | "(" | ")"}`
|
|
||||||
? Arg1NoTrailing | ArgNamesInSQL<SQLAfterArg1>
|
|
||||||
: Arg1 | ArgNamesInSQL<SQLAfterArg1>
|
|
||||||
: SQL extends `${string}$${infer ArgN}`
|
|
||||||
? ArgN extends `${infer ArgNNoTrailing}${";" | "," | "'" | "\"" | "(" | ")"}`
|
|
||||||
? ArgNNoTrailing
|
|
||||||
: ArgN
|
|
||||||
: never;
|
|
||||||
|
|
||||||
type ParametrisedSQL = `${string}$${string}`;
|
|
||||||
type IsPlainSQL<T> = T extends ParametrisedSQL ? never : T;
|
|
||||||
type ArgsForSQL<SQL extends string> = SQL extends ParametrisedSQL
|
|
||||||
? Record<ArgNamesInSQL<SQL>, Interpolable>
|
|
||||||
: JSONObject | undefined;
|
|
||||||
|
|
||||||
// Helper for casting queries
|
|
||||||
export type Q<T extends JSONObject> = Result<T[]>;
|
|
||||||
|
|
||||||
export type WithoutId<T> = Omit<T, "id">;
|
|
||||||
|
|
||||||
export interface StoccaTreDbConn {
|
|
||||||
query<Q extends string>(query: Q, ...args: Q extends IsPlainSQL<Q> ? [(JSONObject | undefined)?] : [ArgsForSQL<Q>]): Promise<Result<JSONObject[]>>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function createNewDbConnection(): Promise<Result<StoccaTreDbConn>> {
|
|
||||||
let postgresClient: Client;
|
|
||||||
try {
|
|
||||||
postgresClient = new Client({
|
|
||||||
user: config.dbUsername,
|
|
||||||
database: "stocca_tre",
|
|
||||||
hostname: config.hostname,
|
|
||||||
port: config.dbPort,
|
|
||||||
password: config.dbPassword,
|
|
||||||
tls: {
|
|
||||||
enabled: false,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
await postgresClient.connect();
|
|
||||||
} catch (e: unknown) {
|
|
||||||
const error = e as { message?: string };
|
|
||||||
if (error.message) {
|
|
||||||
return [new StoccaTreError(error.message).qualified("Error connecting to database: ")];
|
|
||||||
}
|
|
||||||
return [new StoccaTreError("Error connecting to database.")];
|
|
||||||
}
|
|
||||||
return [,
|
|
||||||
{
|
|
||||||
async query<Q extends string>(query: Q, ...args: Q extends IsPlainSQL<Q> ? [(JSONObject | undefined)?] : [ArgsForSQL<Q>]): Promise<Result<JSONObject[]>> {
|
|
||||||
try {
|
|
||||||
const result = <{rows: JSONObject[]}> await postgresClient.queryObject(query, args[0]);
|
|
||||||
return [, result.rows];
|
|
||||||
} catch (e: unknown) {
|
|
||||||
const error = e as { message?: string };
|
|
||||||
return [new StoccaTreError(error.message ?? "Internal database error.")];
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"allowJs": true,
|
|
||||||
"lib": ["deno.window"],
|
|
||||||
"strict": true
|
|
||||||
},
|
|
||||||
"importMap": "./import_map.json",
|
|
||||||
"fmt": {
|
|
||||||
"options": {
|
|
||||||
"useTabs": true,
|
|
||||||
"lineWidth": 120,
|
|
||||||
"indentWidth": 4,
|
|
||||||
"singleQuote": false,
|
|
||||||
"proseWrap": "preserve"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"imports": {
|
|
||||||
"zod": "https://deno.land/x/zod@v3.17.3/mod.ts",
|
|
||||||
"postgres": "https://deno.land/x/postgres@v0.16.1/mod.ts",
|
|
||||||
"bcrypt": "https://deno.land/x/bcrypt@v0.4.0/mod.ts"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
import createNewDbConnection, { StoccaTreDbConn } from "./database.ts";
|
|
||||||
import * as resources from "./resources/main.ts";
|
|
||||||
import config from "./config.ts";
|
|
||||||
import StoccaTreRequest, { HttpMethod } from "./StoccaTreRequest.ts";
|
|
||||||
import { JSONObject } from "./JSON.ts";
|
|
||||||
import StoccaTreServer from "./StoccaTreServer.ts";
|
|
||||||
import {Result, StoccaTreError} from "./Result.ts";
|
|
||||||
|
|
||||||
type StoccaTreApiBody = {
|
|
||||||
data: JSONObject;
|
|
||||||
error?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
function newStoccaTreApiBody(): StoccaTreApiBody {
|
|
||||||
return {
|
|
||||||
data: {},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getJSONBody(request: Request): Promise<Result<JSONObject | null>> {
|
|
||||||
let json;
|
|
||||||
try {
|
|
||||||
if (request.body) {
|
|
||||||
json = await request.json();
|
|
||||||
} else {
|
|
||||||
json = null;
|
|
||||||
}
|
|
||||||
} catch (e: unknown) {
|
|
||||||
return [new StoccaTreError((e as Error).message ?? "Body was invalid JSON.", 400)];
|
|
||||||
}
|
|
||||||
return [, json];
|
|
||||||
}
|
|
||||||
|
|
||||||
async function respondWithError(requestEvent: Deno.RequestEvent, error: StoccaTreError) {
|
|
||||||
const body = newStoccaTreApiBody();
|
|
||||||
await requestEvent.respondWith(
|
|
||||||
Response.json({
|
|
||||||
...body,
|
|
||||||
status: error.status,
|
|
||||||
error: error.qualified("Error: ").message,
|
|
||||||
}, { status: error.status }),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function processRequest(
|
|
||||||
server: StoccaTreServer,
|
|
||||||
requestEvent: Deno.RequestEvent,
|
|
||||||
) {
|
|
||||||
const [bodyError, requestBody] = await getJSONBody(requestEvent.request);
|
|
||||||
if (bodyError) {
|
|
||||||
await respondWithError(requestEvent, bodyError);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const route = /^https?:\/\/[^\/]*(\/.*)$/.exec(requestEvent.request.url)?.[1] ?? "/";
|
|
||||||
const method: HttpMethod = requestEvent.request.method as HttpMethod;
|
|
||||||
const body: StoccaTreApiBody = newStoccaTreApiBody();
|
|
||||||
const [error, result] = await server.handleRequest(new StoccaTreRequest(method, route, requestBody));
|
|
||||||
if (error) {
|
|
||||||
await respondWithError(requestEvent, error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
body.data = result;
|
|
||||||
await requestEvent.respondWith(Response.json(body, { status: 200 }));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const [error, database] = await createNewDbConnection();
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
console.log(error.qualified("Failed to create the database: ").message);
|
|
||||||
} else {
|
|
||||||
const server = new StoccaTreServer(database);
|
|
||||||
server.addResource({ pattern: /ingredient/ }, new resources.IngredientResource(database));
|
|
||||||
server.addResource({ pattern: /user/ }, new resources.UserResource(database));
|
|
||||||
const stoccaTreListener = Deno.listen({ port: config.port ?? 8080 });
|
|
||||||
console.log(`Stocca Tre Server is running. Access it at: http://${ config.hostname }:${ config.port }/`);
|
|
||||||
for await (const conn of stoccaTreListener) {
|
|
||||||
const httpConn = Deno.serveHttp(conn);
|
|
||||||
for await (const requestEvent of httpConn) {
|
|
||||||
await processRequest(server, requestEvent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
1543
server/package-lock.json
generated
Normal file
1543
server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
21
server/package.json
Normal file
21
server/package.json
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"name": "stocca-tre-server",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"scripts": {
|
||||||
|
"start": ". ./.env && ts-node-esm -r tsconfig-paths/register ./src/main.ts"
|
||||||
|
},
|
||||||
|
"author": "Daniel Ledda",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/bcrypt": "^5.0.0",
|
||||||
|
"@types/mysql": "^2.15.21",
|
||||||
|
"@types/node": "^18.11.7",
|
||||||
|
"bcrypt": "^5.1.0",
|
||||||
|
"mysql": "^2.18.1",
|
||||||
|
"ts-node": "^10.9.1",
|
||||||
|
"typescript": "^4.9.1-beta",
|
||||||
|
"zod": "^3.19.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"tsconfig-paths": "^4.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
import { JSONObject } from "../../JSON.ts";
|
|
||||||
import { Q, StoccaTreDbConn } from "../../database.ts";
|
|
||||||
import { Result, StoccaTreError } from "../../Result.ts";
|
|
||||||
|
|
||||||
export const IngredientSchema = z.object({
|
|
||||||
id: z.number(),
|
|
||||||
name: z.string().nonempty(),
|
|
||||||
displayName: z.string().nonempty(),
|
|
||||||
displayNameDE: z.string().nonempty(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const IngredientSchemaWithoutId = IngredientSchema.omit({ id: true });
|
|
||||||
|
|
||||||
export type IngredientModel = z.infer<typeof IngredientSchema>;
|
|
||||||
|
|
||||||
export default class IngredientCollection {
|
|
||||||
static readonly TABLE_NAME = "main.ingredients";
|
|
||||||
private db: StoccaTreDbConn;
|
|
||||||
private mapById: Map<number, IngredientModel> = new Map<number, IngredientModel>();
|
|
||||||
|
|
||||||
constructor(database: StoccaTreDbConn) {
|
|
||||||
this.db = database;
|
|
||||||
}
|
|
||||||
|
|
||||||
async addIngredient(ingredient: JSONObject): Promise<Result<IngredientModel>> {
|
|
||||||
const parsed = IngredientSchemaWithoutId.safeParse(ingredient);
|
|
||||||
if (!ingredient.success) {
|
|
||||||
return [new StoccaTreError("Ingredient definition was malformed.", 400)];
|
|
||||||
}
|
|
||||||
const [error, result] = <Q<IngredientModel>> await this.db.query(
|
|
||||||
`INSERT INTO ${ IngredientCollection.TABLE_NAME } VALUES (DEFAULT, $name, $displayName, $displayNameDE) RETURNING *;`,
|
|
||||||
parsed
|
|
||||||
);
|
|
||||||
if (error) {
|
|
||||||
return [error];
|
|
||||||
}
|
|
||||||
if (result.length > 0) {
|
|
||||||
return [, result[0]];
|
|
||||||
}
|
|
||||||
return [new StoccaTreError("Ingredient wasn't inserted!")];
|
|
||||||
}
|
|
||||||
|
|
||||||
async getById(id: number): Promise<Result<IngredientModel>> {
|
|
||||||
const found = this.mapById.get(id);
|
|
||||||
if (found) {
|
|
||||||
return [, found];
|
|
||||||
}
|
|
||||||
const [error, result] = <Q<IngredientModel>> await this.db.query(`SELECT * FROM ${ IngredientCollection.TABLE_NAME } WHERE id is $id`, { id });
|
|
||||||
if (error) {
|
|
||||||
return [error];
|
|
||||||
}
|
|
||||||
const ingredient = result[0];
|
|
||||||
this.mapById.set(ingredient.id, ingredient);
|
|
||||||
return [, ingredient];
|
|
||||||
}
|
|
||||||
|
|
||||||
async getAllIngredients(): Promise<Result<IngredientModel[]>> {
|
|
||||||
const [error, result] = <Q<IngredientModel>> await this.db.query(`SELECT * FROM ${ IngredientCollection.TABLE_NAME }`);
|
|
||||||
if (!error) {
|
|
||||||
result.forEach((ingredient: IngredientModel) => this.mapById.set(ingredient.id, ingredient));
|
|
||||||
} else {
|
|
||||||
return [error];
|
|
||||||
}
|
|
||||||
return [, Array.from(this.mapById.values())];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
import { StoccaTreDbConn } from "../../database.ts";
|
|
||||||
import IngredientCollection from "./IngredientCollection.ts";
|
|
||||||
import StoccaTreRequest, { RouteDefinition } from "../../StoccaTreRequest.ts";
|
|
||||||
import { Result, StoccaTreError } from "../../Result.ts";
|
|
||||||
import { JSONObject } from "../../JSON.ts";
|
|
||||||
|
|
||||||
export default class IngredientResource {
|
|
||||||
private collection: IngredientCollection;
|
|
||||||
private routes: Readonly<Record<string, RouteDefinition>> = {
|
|
||||||
Add: {
|
|
||||||
pattern: /\/add/,
|
|
||||||
method: "POST",
|
|
||||||
},
|
|
||||||
GetAll: {
|
|
||||||
pattern: /\/all/,
|
|
||||||
method: "GET",
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
constructor(dbConnection: StoccaTreDbConn) {
|
|
||||||
this.collection = new IngredientCollection(dbConnection);
|
|
||||||
}
|
|
||||||
|
|
||||||
async handleRequest(request: StoccaTreRequest): Promise<Result<JSONObject> | null> {
|
|
||||||
let result = null;
|
|
||||||
if (request.match(this.routes.Add) && request.body) {
|
|
||||||
result = await this.collection.addIngredient(request.body);
|
|
||||||
}
|
|
||||||
if (request.match(this.routes.GetAll)) {
|
|
||||||
result = await this.collection.getAllIngredients();
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
export { default as IngredientCollection, type IngredientModel } from "./IngredientCollection.ts";
|
|
||||||
export { default as IngredientResource } from "./IngredientResource.ts";
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
export * from "./user/main.ts";
|
|
||||||
export * from "./ingredient/main.ts";
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import * as bcrypt from "bcrypt";
|
|
||||||
import {Q, StoccaTreDbConn, WithoutId} from "../../database.ts";
|
|
||||||
import { UserModel } from "./UserModel.ts";
|
|
||||||
import {Result, StoccaTreError} from "../../Result.ts";
|
|
||||||
|
|
||||||
const TABLE_NAME = "main.users";
|
|
||||||
|
|
||||||
export default class UserCollection {
|
|
||||||
private db: StoccaTreDbConn;
|
|
||||||
private mapById: Map<number, UserModel> = new Map<number, UserModel>();
|
|
||||||
|
|
||||||
constructor(database: StoccaTreDbConn) {
|
|
||||||
this.db = database;
|
|
||||||
}
|
|
||||||
|
|
||||||
async addUser(user: WithoutId<UserModel>): Promise<Result<{ id: number }>> {
|
|
||||||
let hash: string;
|
|
||||||
try {
|
|
||||||
hash = await bcrypt.hash(user.password);
|
|
||||||
} catch (e: unknown) {
|
|
||||||
const error = e as { message?: string };
|
|
||||||
if (typeof error.message === "string") {
|
|
||||||
return [new StoccaTreError(error.message)];
|
|
||||||
}
|
|
||||||
return [new StoccaTreError("Failed to create user")];
|
|
||||||
}
|
|
||||||
user.password = hash;
|
|
||||||
const [error, users] = <Q<UserModel>> await this.db.query(`INSERT INTO ${TABLE_NAME} ($displayName, $password) RETURNING *`, user);
|
|
||||||
if (error) {
|
|
||||||
return [error];
|
|
||||||
}
|
|
||||||
if (users.length === 0) {
|
|
||||||
return [new StoccaTreError("Failed to insert user.")];
|
|
||||||
}
|
|
||||||
return [, users[0]];
|
|
||||||
}
|
|
||||||
|
|
||||||
async getAllUsers(): Promise<Result<UserModel[]>> {
|
|
||||||
const [error, users] = <Q<UserModel>> await this.db.query(`SELECT * FROM ${TABLE_NAME}`);
|
|
||||||
if (error) {
|
|
||||||
return [error];
|
|
||||||
}
|
|
||||||
users.forEach((user) => this.mapById.set(user.id, user));
|
|
||||||
return [, Array.from(this.mapById.values())];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
export const UserSchema = z.object({
|
|
||||||
id: z.number(),
|
|
||||||
displayName: z.string(),
|
|
||||||
email: z.string().email(),
|
|
||||||
password: z.string().min(256).max(256),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const UserSchemaWithoutId = UserSchema.omit({ id: true });
|
|
||||||
|
|
||||||
export type UserModel = z.infer<typeof UserSchema>;
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
import { StoccaTreDbConn } from "../../database.ts";
|
|
||||||
import StoccaTreRequest, { RouteDefinition } from "../../StoccaTreRequest.ts";
|
|
||||||
import {Result, StoccaTreError} from "../../Result.ts";
|
|
||||||
import { JSONObject } from "../../JSON.ts";
|
|
||||||
import UserCollection from "./UserCollection.ts";
|
|
||||||
import { UserSchemaWithoutId } from "./UserModel.ts";
|
|
||||||
|
|
||||||
export default class UserResource {
|
|
||||||
private dbConnection: StoccaTreDbConn;
|
|
||||||
private collection: UserCollection;
|
|
||||||
private routes: Readonly<Record<string, RouteDefinition>> = {
|
|
||||||
Add: {
|
|
||||||
pattern: /\/add/,
|
|
||||||
method: "POST",
|
|
||||||
},
|
|
||||||
GetAll: {
|
|
||||||
pattern: /\/all/,
|
|
||||||
method: "GET",
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
constructor(dbConnection: StoccaTreDbConn) {
|
|
||||||
this.dbConnection = dbConnection;
|
|
||||||
this.collection = new UserCollection(dbConnection);
|
|
||||||
}
|
|
||||||
|
|
||||||
async handleRequest(request: StoccaTreRequest): Promise<Result<JSONObject> | null> {
|
|
||||||
if (request.match(this.routes.Add)) {
|
|
||||||
return await this.addUser(request);
|
|
||||||
}
|
|
||||||
if (request.match(this.routes.GetAll)) {
|
|
||||||
return await this.allUsers(request);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async addUser(request: StoccaTreRequest): Promise<Result<{ id: number }>> {
|
|
||||||
const user = UserSchemaWithoutId.safeParse(request.body);
|
|
||||||
if (!user.success) {
|
|
||||||
return [new StoccaTreError("User definition was malformed.", 400)];
|
|
||||||
}
|
|
||||||
return await this.collection.addUser(user.data);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async allUsers(request: StoccaTreRequest): Promise<Result<JSONObject>> {
|
|
||||||
const [error, result] = await this.collection.getAllUsers();
|
|
||||||
if (error) {
|
|
||||||
return [error];
|
|
||||||
}
|
|
||||||
return [, { users: result }];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
export * from "./UserModel.ts";
|
|
||||||
export { default as UserCollection } from "./UserCollection.ts";
|
|
||||||
export { default as UserResource } from "./UserResource.ts";
|
|
||||||
59
server/src/InternalRequest.ts
Normal file
59
server/src/InternalRequest.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { URL } from 'url';
|
||||||
|
import { type IncomingMessage, type ServerResponse } from 'http';
|
||||||
|
import { RequestContext } from '@/main';
|
||||||
|
|
||||||
|
export type HttpMethod = "POST" | "GET" | "PUT" | "DELETE" | "PATCH" | "OPTIONS" | "HEAD" | "CONNECT";
|
||||||
|
|
||||||
|
export type RouteDefinition = {
|
||||||
|
pattern: RegExp;
|
||||||
|
method?: HttpMethod;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default class InternalRequest {
|
||||||
|
private onFinish?: (processor: InternalRequest) => void;
|
||||||
|
private bodyBuffer: Buffer;
|
||||||
|
private bodyBufferOffset: number = 0;
|
||||||
|
public method: HttpMethod;
|
||||||
|
public url: URL;
|
||||||
|
public body: string | null = null;
|
||||||
|
public request: IncomingMessage;
|
||||||
|
public response: ServerResponse;
|
||||||
|
public ctx: RequestContext;
|
||||||
|
|
||||||
|
constructor(ctx: RequestContext, request: IncomingMessage, response: ServerResponse) {
|
||||||
|
this.ctx = ctx;
|
||||||
|
this.request = request;
|
||||||
|
this.response = response;
|
||||||
|
this.url = new URL(request.url ?? '/', `http://${ request.headers.host }`);
|
||||||
|
this.method = request.method as HttpMethod ?? 'GET';
|
||||||
|
this.bodyBuffer = Buffer.from(new Uint8Array(Number(request.headers['content-length'] ?? 256)));
|
||||||
|
}
|
||||||
|
|
||||||
|
start(onFinish: (req: InternalRequest) => void) {
|
||||||
|
this.onFinish = onFinish;
|
||||||
|
this.request.on("data", this.bufferRequest.bind(this));
|
||||||
|
this.request.on("end", this.complete.bind(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
private bufferRequest(chunk: Buffer) {
|
||||||
|
this.bodyBuffer.set(chunk, this.bodyBufferOffset);
|
||||||
|
this.bodyBufferOffset += chunk.byteLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
private complete() {
|
||||||
|
let allZero = 0;
|
||||||
|
for (const val of this.bodyBuffer.values()) {
|
||||||
|
allZero |= val;
|
||||||
|
}
|
||||||
|
this.body = allZero !== 0 ? this.bodyBuffer.toString() : null;
|
||||||
|
this.onFinish?.(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
matches(route: RouteDefinition): RegExpExecArray | false {
|
||||||
|
const patternResult = route.pattern.exec(this.url.pathname);
|
||||||
|
if (route.method && route.method !== this.method) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return patternResult ?? false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
type JSONValue =
|
export type JSONValue =
|
||||||
|
| null
|
||||||
| string
|
| string
|
||||||
| number
|
| number
|
||||||
| boolean
|
| boolean
|
||||||
| JSONObject
|
| JSONObject
|
||||||
| JSONArray;
|
| JSONArray;
|
||||||
|
|
||||||
type JSONArray = Array<JSONValue>;
|
export type JSONArray = Array<JSONValue>;
|
||||||
|
|
||||||
export interface JSONObject {
|
export interface JSONObject {
|
||||||
[x: string]: JSONValue;
|
[x: string]: JSONValue;
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
export class StoccaTreError {
|
export class StoccaTreError {
|
||||||
public message: string;
|
message: string;
|
||||||
private statusCode: number = 500;
|
statusCode: number = 500;
|
||||||
|
|
||||||
constructor(message: string, status: number = 500) {
|
constructor(message: string) {
|
||||||
this.message = message;
|
this.message = message;
|
||||||
this.statusCode = 500;
|
this.statusCode = 500;
|
||||||
this.status = status;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
qualified(qualification: string): this {
|
qualified(qualification: string): this {
|
||||||
@@ -16,20 +15,10 @@ export class StoccaTreError {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
get status(): number {
|
|
||||||
return this.statusCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
set status(code: number) {
|
|
||||||
if (code >= 100 && code < 600) {
|
|
||||||
this.statusCode = code;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
withStatus(code: number): this {
|
withStatus(code: number): this {
|
||||||
this.status = code;
|
this.statusCode = code;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Result<T> = [error: undefined, just: T] | [error: StoccaTreError, just?: undefined];
|
export type Result<T> = { error?: never, result: T } | { error: StoccaTreError, result?: undefined };
|
||||||
19
server/src/config.ts
Normal file
19
server/src/config.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
const config = {
|
||||||
|
dbUsername: process.env["DB_USER"] ?? "root",
|
||||||
|
dbHostname: process.env["DB_HOST"] ?? "localhost",
|
||||||
|
dbPassword: process.env["DB_PASS"] ?? "",
|
||||||
|
dbPort: Number(process.env["DB_PORT"] ?? 5432),
|
||||||
|
hostname: process.env["HOST"] ?? "localhost",
|
||||||
|
port: Number(process.env["PORT"] ?? 8080),
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log(`ENV:
|
||||||
|
db username: ${config.dbUsername}
|
||||||
|
db hostname: ${config.dbHostname}
|
||||||
|
db pass: ******
|
||||||
|
db port: ${config.dbPort}
|
||||||
|
server port: ${config.port}
|
||||||
|
server hostname: ${config.hostname}
|
||||||
|
`);
|
||||||
|
|
||||||
|
export default config;
|
||||||
61
server/src/database.ts
Normal file
61
server/src/database.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import { createPool, type Pool, type FieldInfo } from "mysql";
|
||||||
|
import config from "@/config";
|
||||||
|
import { JSONObject, JSONValue } from "@/JSON";
|
||||||
|
import { Result, StoccaTreError } from "@/Result";
|
||||||
|
|
||||||
|
type DBResult<T extends JSONObject> = {
|
||||||
|
data: Array<T> & {
|
||||||
|
affectedRows: number,
|
||||||
|
changedRows: number,
|
||||||
|
insertId?: number,
|
||||||
|
},
|
||||||
|
fields: FieldInfo[],
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WithoutId<T> = Omit<T, "id">;
|
||||||
|
|
||||||
|
export interface StoccaTreDbConn {
|
||||||
|
query<T extends JSONObject>(query: string, values?: JSONValue[] | T): Promise<Result<DBResult<T>>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
class DbConn implements StoccaTreDbConn {
|
||||||
|
constructor(private client: Pool) {}
|
||||||
|
|
||||||
|
async query<T extends JSONObject>(query: string, values?: JSONValue[] | T) {
|
||||||
|
try {
|
||||||
|
const result = await new Promise<DBResult<T>>((res, rej) => {
|
||||||
|
this.client.query({ sql: query, values }, (err, results, fields) => {
|
||||||
|
err ? rej(err) : res({
|
||||||
|
data: results as DBResult<T>['data'],
|
||||||
|
fields: fields ?? [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return { result };
|
||||||
|
} catch (e: unknown) {
|
||||||
|
const error = e as { message?: string };
|
||||||
|
return { error: new StoccaTreError(error.message ?? "unknown error.").qualified("Internal database error: ") };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function createNewDbConnection(): Promise<Result<StoccaTreDbConn>> {
|
||||||
|
let mysqlClient: Pool;
|
||||||
|
try {
|
||||||
|
mysqlClient = createPool({
|
||||||
|
connectionLimit: 10,
|
||||||
|
user: config.dbUsername,
|
||||||
|
database: "stoccatre",
|
||||||
|
port: config.dbPort,
|
||||||
|
password: config.dbPassword,
|
||||||
|
host: config.hostname,
|
||||||
|
});
|
||||||
|
} catch (e: unknown) {
|
||||||
|
const error = e as { message?: string };
|
||||||
|
if (error.message) {
|
||||||
|
return { error: new StoccaTreError(error.message).qualified("Error connecting to database: ") };
|
||||||
|
}
|
||||||
|
return { error: new StoccaTreError("Error connecting to database.") };
|
||||||
|
}
|
||||||
|
return { result: new DbConn(mysqlClient) };
|
||||||
|
}
|
||||||
163
server/src/main.ts
Normal file
163
server/src/main.ts
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import http, { IncomingMessage, ServerResponse } from 'http';
|
||||||
|
import createNewDbConnection, { type StoccaTreDbConn } from "@/database";
|
||||||
|
import IngredientResource, { SubmitIngredientSchema } from "@/resources/ingredient";
|
||||||
|
import UserResource, { UserLoginSchema, UserSignupSchema } from "@/resources/user";
|
||||||
|
import config from "@/config";
|
||||||
|
import InternalRequest, { HttpMethod } from "@/InternalRequest";
|
||||||
|
import { JSONValue } from "@/JSON";
|
||||||
|
import { Result, StoccaTreError } from "@/Result";
|
||||||
|
|
||||||
|
type ApiResponseBody = {
|
||||||
|
data: JSONValue;
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type RequestContext = {
|
||||||
|
resources: {
|
||||||
|
users: UserResource,
|
||||||
|
ingredients: IngredientResource,
|
||||||
|
},
|
||||||
|
regexResult: RegExpMatchArray[] | null,
|
||||||
|
};
|
||||||
|
|
||||||
|
type Route<ValidationSchema extends z.ZodType = z.ZodType> = {
|
||||||
|
method: HttpMethod,
|
||||||
|
regex: RegExp,
|
||||||
|
validate?: ValidationSchema,
|
||||||
|
do: (request: InternalRequest, validatedBody: z.infer<ValidationSchema>) => Promise<Result<JSONValue>>,
|
||||||
|
};
|
||||||
|
|
||||||
|
const routes: Route[] = [
|
||||||
|
{
|
||||||
|
method: "GET",
|
||||||
|
regex: /\/ingredient\/(\d+)/g,
|
||||||
|
do: async (req) => {
|
||||||
|
const id = req.ctx.regexResult?.[0]?.[1];
|
||||||
|
return req.ctx.resources.ingredients.getIngredient(Number(id))
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
method: "GET",
|
||||||
|
regex: /\/user\/(\d+)/g,
|
||||||
|
do: async (req) => {
|
||||||
|
const id = req.ctx.regexResult?.[0]?.[1];
|
||||||
|
return req.ctx.resources.users.getUser(Number(id))
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
validate: SubmitIngredientSchema,
|
||||||
|
regex: /\/ingredient/g,
|
||||||
|
do: async (req, body) => {
|
||||||
|
const { error, result: insertId } = await req.ctx.resources.ingredients.addIngredient(body);
|
||||||
|
if (error) return { error };
|
||||||
|
return { result: { id: insertId }};
|
||||||
|
},
|
||||||
|
} satisfies Route<typeof SubmitIngredientSchema>,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
validate: UserLoginSchema,
|
||||||
|
regex: /\/user\/login/g,
|
||||||
|
do: async (req, body) => {
|
||||||
|
const { error, result: wasAuthenticated } = await req.ctx.resources.users.authUser(body);
|
||||||
|
if (error) {
|
||||||
|
return { error: error.qualified("Error logging in: ") };
|
||||||
|
}
|
||||||
|
return { result: { loggedIn: wasAuthenticated }};
|
||||||
|
},
|
||||||
|
} satisfies Route<typeof UserLoginSchema>,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
validate: UserSignupSchema,
|
||||||
|
regex: /\/user/g,
|
||||||
|
do: async (req) => req.ctx.resources.users.addUser(req.body ? JSON.parse(req.body) : null),
|
||||||
|
} satisfies Route<typeof UserSignupSchema>,
|
||||||
|
{
|
||||||
|
method: "GET",
|
||||||
|
regex: /\/ingredients/g,
|
||||||
|
do: async (req) => req.ctx.resources.ingredients.getAllIngredients(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function newApiBody(): ApiResponseBody {
|
||||||
|
return {
|
||||||
|
data: {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function route(req: InternalRequest): Promise<Result<JSONValue>> {
|
||||||
|
let method = req.method;
|
||||||
|
let result: Result<JSONValue> | null = null;
|
||||||
|
for (const route of routes) {
|
||||||
|
if (route.method === method || !route.method && method === "GET") {
|
||||||
|
const matches = Array.from(req.url.pathname.matchAll(route.regex));
|
||||||
|
if (matches.length > 0) {
|
||||||
|
req.ctx.regexResult = matches;
|
||||||
|
if (req.body && route.validate) {
|
||||||
|
const obj = JSON.parse(req.body);
|
||||||
|
const parse = route.validate.safeParse(obj);
|
||||||
|
if (!parse.success) {
|
||||||
|
result = { error: new StoccaTreError("Invalid body.").withStatus(400) };
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
result = await route.do(req, parse.data);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result = await route.do(req, undefined);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (result) return result;
|
||||||
|
return { error: new StoccaTreError('Invalid route.').withStatus(400) };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function processRequestResult(request: InternalRequest) {
|
||||||
|
const { error, result: requestData } = await route(request);
|
||||||
|
const response = request.response;
|
||||||
|
response.setHeader('Content-Type', 'application/json');
|
||||||
|
const responseBody = newApiBody();
|
||||||
|
if (error) {
|
||||||
|
responseBody.error = error.message;
|
||||||
|
response.statusCode = error.statusCode;
|
||||||
|
} else {
|
||||||
|
responseBody.data = requestData;
|
||||||
|
response.statusCode = 200;
|
||||||
|
}
|
||||||
|
response.write(JSON.stringify(responseBody));
|
||||||
|
response.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const { error, result: dbConnection } = await createNewDbConnection();
|
||||||
|
if (error) {
|
||||||
|
console.log(error.qualified("Failed to create the database: ").message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const resources = {
|
||||||
|
ingredients: new IngredientResource(dbConnection),
|
||||||
|
users: new UserResource(dbConnection),
|
||||||
|
};
|
||||||
|
|
||||||
|
const server = http.createServer((req, res) => {
|
||||||
|
const ctx: RequestContext = {
|
||||||
|
resources,
|
||||||
|
regexResult: null,
|
||||||
|
};
|
||||||
|
const internalReq = new InternalRequest(ctx, req, res);
|
||||||
|
internalReq.start(processRequestResult);
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
server.listen({ port: config.port ?? 8080 });
|
||||||
|
} catch (e) {
|
||||||
|
console.error(new StoccaTreError((e as Error).message ?? "").qualified("Failed to start fastify server: "));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log(`Stocca Tre Server is running. Access it at: http://${ config.hostname }:${ config.port }/`);
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
||||||
48
server/src/resources/ingredient.ts
Normal file
48
server/src/resources/ingredient.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import { StoccaTreDbConn } from "@/database";
|
||||||
|
import { Result, StoccaTreError } from "@/Result";
|
||||||
|
|
||||||
|
export const IngredientSchema = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string().min(1),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const SubmitIngredientSchema = IngredientSchema.omit({ id: true });
|
||||||
|
|
||||||
|
export type SubmitIngredientModel = z.infer<typeof SubmitIngredientSchema>;
|
||||||
|
export type IngredientModel = z.infer<typeof IngredientSchema>;
|
||||||
|
|
||||||
|
const TABLE_NAME = "ingredients";
|
||||||
|
export default class IngredientResource {
|
||||||
|
private db: StoccaTreDbConn;
|
||||||
|
private mapById: Map<number, IngredientModel> = new Map<number, IngredientModel>();
|
||||||
|
|
||||||
|
constructor(database: StoccaTreDbConn) {
|
||||||
|
this.db = database;
|
||||||
|
}
|
||||||
|
|
||||||
|
async addIngredient(ingredient: SubmitIngredientModel): Promise<Result<number | null>> {
|
||||||
|
const query = await this.db.query(`INSERT INTO ${ TABLE_NAME } (name) VALUES (?)`, [ ingredient.name ]);
|
||||||
|
if (query.error) return query;
|
||||||
|
return { result: query.result.data.insertId ?? null };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getIngredient(id: number): Promise<Result<IngredientModel | null>> {
|
||||||
|
const query = await this.db.query<IngredientModel>(`SELECT id, name FROM ${ TABLE_NAME } WHERE id = ?`, [id]);
|
||||||
|
if (query.error) return query;
|
||||||
|
if (!query.result.data[0]) {
|
||||||
|
return { error: new StoccaTreError("Ingredient not found.").withStatus(404) };
|
||||||
|
}
|
||||||
|
return { result: query.result.data[0] };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAllIngredients(): Promise<Result<IngredientModel[]>> {
|
||||||
|
const query = await this.db.query<IngredientModel>(`SELECT * FROM ${ TABLE_NAME }`);
|
||||||
|
if (!query.error) {
|
||||||
|
query.result.data.forEach((ingredient: IngredientModel) => this.mapById.set(ingredient.id, ingredient));
|
||||||
|
} else {
|
||||||
|
return query;
|
||||||
|
}
|
||||||
|
return { result: Array.from(this.mapById.values()) };
|
||||||
|
}
|
||||||
|
}
|
||||||
79
server/src/resources/user.ts
Normal file
79
server/src/resources/user.ts
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import * as bcrypt from "bcrypt";
|
||||||
|
import { StoccaTreDbConn, WithoutId } from "@/database";
|
||||||
|
import { Result, StoccaTreError } from "@/Result";
|
||||||
|
|
||||||
|
export const UserSchema = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
username: z.string(),
|
||||||
|
email: z.string().email(),
|
||||||
|
password: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const UserSignupSchema = UserSchema.omit({ id: true });
|
||||||
|
|
||||||
|
export const UserLoginSchema = z.object({
|
||||||
|
username: z.string(),
|
||||||
|
password: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type UserSignupModel = z.infer<typeof UserSignupSchema>;
|
||||||
|
export type UserLoginModel = z.infer<typeof UserLoginSchema>;
|
||||||
|
export type UserModel = z.infer<typeof UserSchema>;
|
||||||
|
|
||||||
|
const TABLE_NAME = "users";
|
||||||
|
export default class UserResource {
|
||||||
|
private db: StoccaTreDbConn;
|
||||||
|
private mapById: Map<number, UserModel> = new Map<number, UserModel>();
|
||||||
|
|
||||||
|
constructor(database: StoccaTreDbConn) {
|
||||||
|
this.db = database;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async hash(pw: string) {
|
||||||
|
const salt = await bcrypt.genSalt(10);
|
||||||
|
return await bcrypt.hash(pw, salt);
|
||||||
|
}
|
||||||
|
|
||||||
|
async addUser(user: UserSignupModel): Promise<Result<number | null>> {
|
||||||
|
let hash: string;
|
||||||
|
try {
|
||||||
|
hash = await this.hash(user.password);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
const error = e as { message?: string };
|
||||||
|
return { error: new StoccaTreError(error.message ?? "Failed to create user") };
|
||||||
|
}
|
||||||
|
user.password = hash;
|
||||||
|
const query = await this.db.query(
|
||||||
|
`INSERT INTO ${ TABLE_NAME } (username, password, email) VALUES (?, ?, ?)`,
|
||||||
|
[user.username, user.password, user.email],
|
||||||
|
);
|
||||||
|
if (query.error) return query;
|
||||||
|
return { result: query.result.data.insertId ?? null };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAllUsers(): Promise<Result<UserModel[]>> {
|
||||||
|
const query = await this.db.query<UserModel>(`SELECT * FROM ${ TABLE_NAME }`);
|
||||||
|
if (query.error) return query;
|
||||||
|
query.result.data.forEach((user) => this.mapById.set(user.id, user));
|
||||||
|
return { result: Array.from(this.mapById.values()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUser(id: number): Promise<Result<UserModel | null>> {
|
||||||
|
const query = await this.db.query<UserModel>(`SELECT id, username, email FROM ${ TABLE_NAME } WHERE id = ?`, [id]);
|
||||||
|
if (query.error) return query;
|
||||||
|
if (!query.result.data[0]) {
|
||||||
|
return { error: new StoccaTreError("User not found.").withStatus(404) };
|
||||||
|
}
|
||||||
|
return { result: query.result.data[0] };
|
||||||
|
}
|
||||||
|
|
||||||
|
async authUser(user: UserLoginModel): Promise<Result<boolean>> {
|
||||||
|
const query = await this.db.query<UserModel>(`SELECT password FROM ${ TABLE_NAME } WHERE username = ?`, [user.username]);
|
||||||
|
if (query.error) return query;
|
||||||
|
if (query.result.data[0]) {
|
||||||
|
return { result: await bcrypt.compare(user.password, query.result.data[0].password) };
|
||||||
|
}
|
||||||
|
return { error: new StoccaTreError(`Could not authenticate user.`).withStatus(404) };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1 +0,0 @@
|
|||||||
DB_USER=postgres DB_PASS=postgres deno run --allow-read --allow-env --allow-net --import-map=import_map.json main.ts
|
|
||||||
79
server/tsconfig.json
Normal file
79
server/tsconfig.json
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
/* Visit https://aka.ms/tsconfig.json to read more about this file */
|
||||||
|
|
||||||
|
/* Basic Options */
|
||||||
|
// "incremental": true, /* Enable incremental compilation */
|
||||||
|
"target": "ES2020", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
|
||||||
|
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
|
||||||
|
//"lib": [], /* Specify library files to be included in the compilation. */
|
||||||
|
"allowJs": true, /* Allow javascript files to be compiled. */
|
||||||
|
// "checkJs": true, /* Report errors in .js files. */
|
||||||
|
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
|
||||||
|
"jsxFactory": "h",
|
||||||
|
"jsxFragmentFactory": "frag",
|
||||||
|
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
||||||
|
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
|
||||||
|
// "sourceMap": true, /* Generates corresponding '.map' file. */
|
||||||
|
// "outFile": "./", /* Concatenate and emit output to single file. */
|
||||||
|
"outDir": "./dist", /* Redirect output structure to the directory. */
|
||||||
|
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
||||||
|
// "composite": true, /* Enable project compilation */
|
||||||
|
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
|
||||||
|
// "removeComments": true, /* Do not emit comments to output. */
|
||||||
|
// "noEmit": true, /* Do not emit outputs. */
|
||||||
|
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
||||||
|
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
||||||
|
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
||||||
|
|
||||||
|
/* Strict Type-Checking Options */
|
||||||
|
"strict": true, /* Enable all strict type-checking options. */
|
||||||
|
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
|
||||||
|
// "strictNullChecks": true, /* Enable strict null checks. */
|
||||||
|
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
|
||||||
|
"strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
|
||||||
|
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
|
||||||
|
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
||||||
|
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
||||||
|
|
||||||
|
/* Additional Checks */
|
||||||
|
// "noUnusedLocals": true, /* Report errors on unused locals. */
|
||||||
|
// "noUnusedParameters": true, /* Report errors on unused parameters. */
|
||||||
|
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
||||||
|
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
||||||
|
"noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
|
||||||
|
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
|
||||||
|
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
|
||||||
|
|
||||||
|
/* Module Resolution Options */
|
||||||
|
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
||||||
|
"baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"],
|
||||||
|
}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
||||||
|
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
||||||
|
// "typeRoots": [], /* List of folders to include type definitions from. */
|
||||||
|
// "types": [], /* Type declaration files to be included in compilation. */
|
||||||
|
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
||||||
|
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
|
||||||
|
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
||||||
|
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||||
|
|
||||||
|
/* Source Map Options */
|
||||||
|
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
||||||
|
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||||
|
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
||||||
|
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
||||||
|
|
||||||
|
/* Experimental Options */
|
||||||
|
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
||||||
|
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
||||||
|
|
||||||
|
/* Advanced Options */
|
||||||
|
"skipLibCheck": true, /* Skip type checking of declaration files. */
|
||||||
|
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"./src/**/*"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -6,10 +6,10 @@
|
|||||||
// "incremental": true, /* Enable incremental compilation */
|
// "incremental": true, /* Enable incremental compilation */
|
||||||
"target": "ES6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
|
"target": "ES6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
|
||||||
"module": "es2020", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
|
"module": "es2020", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
|
||||||
// "lib": [""], /* Specify library files to be included in the compilation. */
|
//"lib": [], /* Specify library files to be included in the compilation. */
|
||||||
"allowJs": true, /* Allow javascript files to be compiled. */
|
"allowJs": true, /* Allow javascript files to be compiled. */
|
||||||
// "checkJs": true, /* Report errors in .js files. */
|
// "checkJs": true, /* Report errors in .js files. */
|
||||||
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
|
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
|
||||||
"jsxFactory": "h",
|
"jsxFactory": "h",
|
||||||
"jsxFragmentFactory": "frag",
|
"jsxFragmentFactory": "frag",
|
||||||
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
||||||
Reference in New Issue
Block a user