Skip to content

Commit

Permalink
Add framework config and Fastify WS
Browse files Browse the repository at this point in the history
  • Loading branch information
DemianParkhomenko committed Sep 26, 2023
1 parent 3ed62aa commit 07ec570
Show file tree
Hide file tree
Showing 13 changed files with 100 additions and 59 deletions.
3 changes: 2 additions & 1 deletion config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ module.exports = {
api: {
path: './api',
port: 8001,
transport: 'ws',
framework: 'native',
transport: 'http',
},
static: {
port: 8000,
Expand Down
15 changes: 4 additions & 11 deletions lib/transport/fastify.js → lib/framework/fastify/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ const fastify = require('fastify')({
logger: false,
});
const cors = require('@fastify/cors');
const { HEADERS } = require('./headers.js');
const { HEADERS } = require('../headers.js');
const start = require('./start.js');

const setup = async (routing) => {
const services = Object.keys(routing);
Expand All @@ -23,17 +24,9 @@ const setup = async (routing) => {
}
};

const start = async (port) => {
try {
await fastify.listen({ port });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};

module.exports = async (routing, port) => {
await fastify.register(cors, HEADERS);
await setup(routing);
await start(port);
await start(fastify, port, console);
console.log('Fastify HTTP 🔌');
};
8 changes: 8 additions & 0 deletions lib/framework/fastify/start.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = async (fastify, port, console) => {
try {
await fastify.listen({ port });
} catch (err) {
console.error(err);
process.exit(1);
}
};
22 changes: 22 additions & 0 deletions lib/framework/fastify/ws.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict';

const fastify = require('fastify')();
const start = require('./start.js');
const handler = require('../ws-handler.js');

const setup = async (routing) => {
fastify.register(async (fastify) => {
fastify.get('*', { websocket: true }, ({ socket }) => {
socket.on('message', (message) =>
handler({ routing, socket, console, message })
);
});
});
};

module.exports = async (routing, port, console) => {
fastify.register(require('@fastify/websocket'));
await setup(routing);
await start(fastify, port, console);
console.log('🔌 Fastify WS');
};
File renamed without changes.
3 changes: 2 additions & 1 deletion lib/transport/http.js → lib/framework/native/http.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';

const http = require('node:http');
const { HEADERS } = require('./headers.js');
const { HEADERS } = require('../headers.js');

const parseBody = async (req) => {
const buffer = [];
Expand All @@ -27,4 +27,5 @@ module.exports = (routing, port, console) => {
res.end(JSON.stringify(result));
})
.listen(port);
console.log('Native HTTP 🔌');
};
14 changes: 14 additions & 0 deletions lib/framework/native/ws.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

const { Server } = require('ws');
const handler = require('../ws-handler.js');

module.exports = (routing, port, console) => {
const ws = new Server({ port });
ws.on('connection', (socket) => {
socket.on('message', async (message) =>
handler({ routing, socket, console, message })
);
});
console.log('🔌 Native WS');
};
27 changes: 27 additions & 0 deletions lib/framework/ws-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const handler = async ({ routing, socket, console, message }) => {
const send = (result) => {
socket.send(JSON.stringify(result), { binary: false });
};
const obj = JSON.parse(message);
const { name, method, args = [] } = obj;
const entity = routing[name];
if (!entity) {
send({ error: 'Entity not found' });
return;
}
const handler = entity[method];
if (!handler) {
send({ error: 'Handler hot found' });
return;
}
try {
const result = await handler(...args);
send(result);
} catch (err) {
console.error(err);
send({ error: 'Server error' });
}
};

// TODO: unify and create http-handler.js
module.exports = handler;
19 changes: 9 additions & 10 deletions lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,22 @@ const fsp = require('node:fs/promises');
const path = require('node:path');
const config = require('../config/index.js');
const crud = require('./db/crud.js');
const load = require('./utils/load.js')(config.sandbox);
const deepFreeze = require('./utils/freeze.js');
const staticServer = require('./static/server.js');
const server = require(`./transport/${config.api.transport}.js`);
const console = require(`./logger/${config.logger.name}.js`)(config.logger);
console.info(`📝 Logger ${config.logger.name} started`);
const server = require(
`./framework/${config.api.framework}/${config.api.transport}.js`
);
const load = require('./utils/load.js')(config.sandbox);
const logger = require(`./logger/${config.logger.name}.js`);
const startDb = require('./db/start.js');

const start = async () => {
const console = logger(config.logger);
console.info(`📝 Logger ${config.logger.name} started`);
const db = await startDb(config.db);
console.info('✅ Connected to database');
const sandbox = {
console: deepFreeze(console),
//? Can not be frozen because of prisma
db,
crud: deepFreeze(crud),
};
//? Db can not be frozen because of Prisma
const sandbox = { console: deepFreeze(console), db, crud: deepFreeze(crud) };
const apiPath = path.join(process.cwd(), config.api.path);
const routing = {};
const files = await fsp.readdir(apiPath);
Expand Down
35 changes: 0 additions & 35 deletions lib/transport/ws.js

This file was deleted.

10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"license": "MIT",
"dependencies": {
"@fastify/cors": "^8.3.0",
"@fastify/websocket": "^8.2.0",
"@prisma/client": "^5.3.1",
"fastify": "^4.23.2",
"pg": "^8.8.0",
Expand Down
2 changes: 1 addition & 1 deletion static/client.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

const url = new URL('ws://localhost:8001');
const url = new URL('http://localhost:8001');
const structure = {
user: {
create: ['record'],
Expand Down

0 comments on commit 07ec570

Please sign in to comment.