Skip to content

Commit

Permalink
fix http not PUT req
Browse files Browse the repository at this point in the history
  • Loading branch information
axbuglak committed Sep 2, 2023
1 parent 4de1259 commit 904ead5
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 42 deletions.
24 changes: 1 addition & 23 deletions JavaScript/c-commonjs/static.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,12 @@ const http = require('node:http');
const path = require('node:path');
const fs = require('node:fs');

const MIME_TYPES = {
html: 'text/html; charset=UTF-8',
json: 'application/json; charset=UTF-8',
js: 'application/javascript; charset=UTF-8',
css: 'text/css',
png: 'image/png',
ico: 'image/x-icon',
svg: 'image/svg+xml',
};

const HEADERS = {
'X-XSS-Protection': '1; mode=block',
'X-Content-Type-Options': 'nosniff',
'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
};

module.exports = (root, port, console) => {
http.createServer(async (req, res) => {
const url = req.url === '/' ? '/index.html' : req.url;
const filePath = path.join(root, url);
try {
const data = await fs.promises.readFile(filePath);
const fileExt = path.extname(filePath).substring(1);
const mimeType = MIME_TYPES[fileExt] || MIME_TYPES.html;
res.writeHead(200, { ...HEADERS, 'Content-Type': mimeType });
res.end(data);
} catch (err) {
res.statusCode = 404;
Expand All @@ -40,4 +18,4 @@ module.exports = (root, port, console) => {
}).listen(port);

console.log(`Static on port ${port}`);
};
};
21 changes: 11 additions & 10 deletions JavaScript/c-commonjs/static/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const transport = {};

transport.http = (url) => (structure) => {
transport.http = url => structure => {
const api = {};
const services = Object.keys(structure);
for (const name of services) {
Expand All @@ -11,21 +11,22 @@ transport.http = (url) => (structure) => {
const methods = Object.keys(service);
for (const method of methods) {
api[name][method] = (...args) => new Promise((resolve, reject) => {
fetch(`${url}/api/${name}/${method}`, {
fetch(`${url}/${name}/${method}/${args}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ args }),
}).then((res) => {
}).then(res => {
if (res.status === 200) resolve(res.json());
else reject(new Error(`Status Code: ${res.status}`));
});
});
}
}
console.log(api);
return Promise.resolve(api);
};

transport.ws = (url) => (structure) => {
transport.ws = url => structure => {
const socket = new WebSocket(url);
const api = {};
const services = Object.keys(structure);
Expand All @@ -34,28 +35,28 @@ transport.ws = (url) => (structure) => {
const service = structure[name];
const methods = Object.keys(service);
for (const method of methods) {
api[name][method] = (...args) => new Promise((resolve) => {
api[name][method] = (...args) => new Promise(resolve => {
const packet = { name, method, args };
socket.send(JSON.stringify(packet));
socket.onmessage = (event) => {
socket.onmessage = event => {
const data = JSON.parse(event.data);
resolve(data);
};
});
}
}
return new Promise((resolve) => {
return new Promise(resolve => {
socket.addEventListener('open', () => resolve(api));
});
};

const scaffold = (url) => {
const scaffold = url => {
const protocol = url.startsWith('ws:') ? 'ws' : 'http';
return transport[protocol](url);
};

(async () => {
const api = await scaffold('http://localhost:8001')({
const api = await scaffold('ws://localhost:8001')({
user: {
create: ['record'],
read: ['id'],
Expand All @@ -72,6 +73,6 @@ const scaffold = (url) => {
say: ['message'],
}
});
const data = await api.talks.say('hello');
const data = await api.user.read(3);
console.dir({ data });
})();
16 changes: 9 additions & 7 deletions JavaScript/c-commonjs/transport/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const HEADERS = {
'Content-Type': 'application/json; charset=UTF-8',
};

const receiveArgs = async (req) => {
const receiveArgs = async req => {
const buffers = [];
for await (const chunk of req) buffers.push(chunk);
const data = Buffer.concat(buffers).toString();
Expand All @@ -22,18 +22,20 @@ const receiveArgs = async (req) => {
module.exports = (routing, port, console) => {
http.createServer(async (req, res) => {
res.writeHead(200, HEADERS);
if (req.method !== 'POST') return void res.end('"Not found"');
const { url, socket } = req;
const [place, name, method] = url.substring(1).split('/');
if (place !== 'api') return void res.end('"Not found"');
const [name, method, id] = url.substring(1).split('/');
const entity = routing[name];
if (!entity) return void res.end('"Not found"');
const handler = entity[method];
if (!handler) return void res.end('"Not found"');
const { args } = await receiveArgs(req);
const src = handler.toString();
const signature = src.substring(0, src.indexOf(')'));
const args = [];
if (signature.includes('(id')) args.push(id);
if (signature.includes('{')) args.push(await receiveArgs(req));
console.log(`${socket.remoteAddress} ${method} ${url}`);
const result = await handler(args);
res.end(JSON.stringify(result));
const result = await handler(...args);
res.end(JSON.stringify(result.rows ? result.rows : result));
}).listen(port);

console.log(`API on port ${port}`);
Expand Down
4 changes: 2 additions & 2 deletions JavaScript/c-commonjs/transport/ws.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module.exports = (routing, port, console) => {

ws.on('connection', (connection, req) => {
const ip = req.socket.remoteAddress;
connection.on('message', async (message) => {
connection.on('message', async message => {
const obj = JSON.parse(message);
const { name, method, args = [] } = obj;
const entity = routing[name];
Expand All @@ -25,7 +25,7 @@ module.exports = (routing, port, console) => {
console.log(`${ip} ${name}.${method}(${parameters})`);
try {
const result = await handler(...args);
connection.send(JSON.stringify(result), { binary: false });
connection.send(JSON.stringify(result.rows ? result.rows : result), { binary: false });
} catch (err) {
console.error(err);
connection.send('"Server error"', { binary: false });
Expand Down

0 comments on commit 904ead5

Please sign in to comment.