Skip to content

Commit

Permalink
Add typescript and fix errors
Browse files Browse the repository at this point in the history
  • Loading branch information
DemianParkhomenko committed Oct 1, 2023
1 parent d3753e6 commit 6624354
Show file tree
Hide file tree
Showing 15 changed files with 118 additions and 70 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ jobs:
node-version: '20.x'
cache: 'npm'
- run: npm ci
- run: npm run format:check
- run: npm run lint:check
- run: npm run prettier:check
- run: npm run eslint:check
- run: npm run test
deploy:
runs-on: ubuntu-latest
Expand Down
5 changes: 5 additions & 0 deletions .lintstagedrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
'*': 'prettier --check --ignore-unknown',
'*.js': 'eslint --cache',
'*.{js,ts}': () => 'npm run typescript:check',
};
2 changes: 1 addition & 1 deletion api/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
...crud('user'),
read: async () => {
console.warn('🚨 This is a warning');
return await await db.user.findMany();
return await db.user.findMany();
},
});
25 changes: 25 additions & 0 deletions global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import Prisma from '@prisma/client';

type ModelName = 'user' | 'message' | 'chat';

type PrismaModels = {
user: Prisma.User;
message: Prisma.Message;
chat: Prisma.Chat;
};

interface Crud {
<T extends ModelName>(
modelName: T
): {
read(id?: number): Promise<PrismaModels[T][]>;
create(record: PrismaModels[T]): Promise<PrismaModels[T]>;
update(id: number, record: Partial<PrismaModels[T]>): PrismaModels[T];
delete(id: number): PrismaModels[T];
};
}

declare global {
const db: Prisma.PrismaClient;
const crud: Crud;
}
58 changes: 32 additions & 26 deletions lib/db/crud.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,41 @@
// @ts-nocheck
const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

const crud = (model) => ({
async read(id) {
if (!id) {
return await prisma[model].findMany();
}
return prisma[model].findUnique({
where: { id },
});
},
const crud = (modelName) => {
const model = prisma[modelName];
if (!model) {
throw new Error(`Model ${modelName} does not exist`);
}

async create(record) {
return prisma[model].create({
data: record,
});
},
return {
async create(record) {
return await model.create({
data: record,
});
},

async update(id, record) {
return prisma[model].update({
where: { id },
data: record,
});
},
async read(id) {
if (!id) return await model.findMany();
return await model.findUnique({
where: { id },
});
},

async delete(id) {
return prisma[model].delete({
where: { id },
});
},
});
async update(id, record) {
return await model.update({
where: { id },
data: record,
});
},

async delete(id) {
return await model.delete({
where: { id },
});
},
};
};

module.exports = crud;
3 changes: 0 additions & 3 deletions lib/db/start.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
'use strict';

/**
* @typedef { import("@prisma/client").User} User
*/
const { PrismaClient } = require('@prisma/client');

const start = async (config) => {
Expand Down
5 changes: 3 additions & 2 deletions lib/framework/fastify/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ const fastify = require('fastify')({
logger: false,
});
const cors = require('@fastify/cors');
const { HEADERS } = require('../headers.js');
const start = require('./start.js');

const setup = async (routing) => {
Expand All @@ -17,6 +16,8 @@ const setup = async (routing) => {
if (!entity) return reply.code(404).send('Not found');
const handler = entity[methodName];
if (!handler) return reply.code(404).send('Not found');
if (!Array.isArray(request.body))
return reply.code(400).send('Bad request');
const result = await handler(...request.body);
reply.code(200).send(result);
});
Expand All @@ -25,7 +26,7 @@ const setup = async (routing) => {
};

module.exports = async (routing, port) => {
await fastify.register(cors, HEADERS);
await fastify.register(cors);
await setup(routing);
await start(fastify, port, console);
console.log('Fastify HTTP 🔌');
Expand Down
8 changes: 0 additions & 8 deletions lib/framework/headers.js

This file was deleted.

9 changes: 7 additions & 2 deletions lib/framework/native/http.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
'use strict';

const http = require('node:http');
const { HEADERS } = require('../headers.js');
const HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': 600,
};

const parseBody = async (req) => {
const buffer = [];
Expand All @@ -16,7 +21,7 @@ module.exports = (routing, port, console) => {
res.writeHead(200, HEADERS);
if (req.method !== 'POST') return void res.end('"Not found"');
const { url, socket } = req;
const [name, method] = url.substring(1).split('/');
const [name, method] = url?.substring(1).split('/') ?? [];
const entity = routing[name];
if (!entity) return void res.end('Not found');
const handler = entity[method];
Expand Down
13 changes: 8 additions & 5 deletions lib/logger/pino.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
const pino = require('pino');
const { pino } = require('pino');

module.exports = (config) => {
const targets = [];
if (config.console) {
targets.push({
level: 'trace',
target: 'pino-pretty',
options: {
colorize: true,
},
});
}
if (config.fsPath) {
Expand All @@ -25,16 +28,16 @@ module.exports = (config) => {
return {
log(...args) {
// TODO: issue https://github.com/pinojs/pino-pretty/issues/455
logger.info(...args);
logger.info(args);
},
info(...args) {
logger.info(...args);
logger.info(args);
},
warn(...args) {
logger.warn(...args);
logger.warn(args);
},
error(...args) {
logger.error(...args);
logger.error(args);
},
};
};
8 changes: 4 additions & 4 deletions lib/logger/winston.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,16 @@ module.exports = (config) => {

return {
log(...args) {
logger.verbose(...args);
logger.verbose(args);
},
info(...args) {
logger.info(...args);
logger.info(args);
},
warn(...args) {
logger.warn(...args);
logger.warn(args);
},
error(...args) {
logger.error(...args);
logger.error(args);
},
};
};
2 changes: 1 addition & 1 deletion lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const start = async () => {
const serviceName = path.basename(fileName, '.js');
routing[serviceName] = await load(filePath, sandbox);
}
staticServer('./static', config.static.port, console);
staticServer('./static', config.static.port);
console.info(`📦 Static server on ${config.static.port}`);
server(routing, config.api.port, console);
console.info(`🚀 API server no ${config.api.port}`);
Expand Down
4 changes: 4 additions & 0 deletions lib/static/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ module.exports = (root, port) => {
http
.createServer(async (req, res) => {
const url = req.url === '/' ? '/index.html' : req.url;
if (!url) {
res.end('Invalid URL');
return;
}
const filePath = path.join(root, url);
try {
const data = await fs.promises.readFile(filePath);
Expand Down
15 changes: 6 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,18 @@
"description": "Learn Node.js with fun🤪",
"main": "index.js",
"type": "commonjs",
"types": "./global.d.ts",
"scripts": {
"start": "node ./lib/main.js",
"dev": "nodemon ./lib/main.js",
"test": "echo no test specified",
"lint:check": "eslint .",
"lint:write": "eslint --fix .",
"format:check": "prettier --check .",
"format:write": "prettier --write .",
"eslint:check": "eslint .",
"eslint:write": "eslint --fix .",
"prettier:check": "prettier --check .",
"prettier:write": "prettier --write .",
"typescript:check": "tsc -p tsconfig.json",
"prepare": "husky install"
},
"lint-staged": {
"*": "prettier --write --ignore-unknown",
"*.js": "eslint",
"*.ts": "eslint"
},
"author": "",
"license": "MIT",
"dependencies": {
Expand Down
27 changes: 20 additions & 7 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
{
"compilerOptions": {
"target": "ESNext",
"noEmit": true,
"checkJs": true,
"target": "ES2022",
"module": "CommonJS",
"lib": ["ES2022"],
"esModuleInterop": true,
"isolatedModules": true,
"moduleResolution": "node",

"emitDecoratorMetadata": false,
"experimentalDecorators": false,

"strict": true,
"baseUrl": ".",
"preserveWatchOutput": true,
"allowJs": true,
"noEmit": true,
"skipLibCheck": true
"alwaysStrict": true,
"allowUnreachableCode": true,
"allowUnusedLabels": true,
"noImplicitAny": false,
"noImplicitReturns": true,
"resolveJsonModule": true,

"declaration": true
},
"include": ["*", "**/*"]
"exclude": ["node_modules", "static"]
}

0 comments on commit 6624354

Please sign in to comment.