Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
sergeyampo committed Dec 19, 2023
1 parent c0af13d commit 850c07f
Show file tree
Hide file tree
Showing 19 changed files with 782 additions and 317 deletions.
5 changes: 5 additions & 0 deletions JavaScript/9-logger/api.di.container.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
common: Object.freeze({hash: require('./hash')}),
db: Object.freeze(require('./db')),
console: Object.freeze(require('./logger.di.container')),
};
5 changes: 4 additions & 1 deletion JavaScript/9-logger/api/city.js
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
db('city');
'use strict';
const {db} = require('../api.di.container');

module.exports = db('city');
24 changes: 14 additions & 10 deletions JavaScript/9-logger/api/country.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
'use strict';
const { db } = require('../api.di.container');
const { console } = require('../api.di.container');

const country = db('country');

({
async read(id) {
console.log({ db });
return await country.read(id);
},
module.exports = {
async read(id) {
console.log({ db });
return await country.read(id);
},

async find(mask) {
const sql = 'SELECT * from country where name like $1';
return await country.query(sql, [mask]);
},
});
async find(mask) {
const sql = 'SELECT * from country where name like $1';
return await country.query(sql, [mask]);
},
};
43 changes: 23 additions & 20 deletions JavaScript/9-logger/api/user.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
({
async read(id) {
return await db('users').read(id, ['id', 'login']);
},
'use strict';
const {db, common} = require('../api.di.container');

async create({ login, password }) {
const passwordHash = await common.hash(password);
return await db('users').create({ login, password: passwordHash });
},
module.exports = {
async read(id) {
return await db('users').read(id, ['id', 'login']);
},

async update(id, { login, password }) {
const passwordHash = await common.hash(password);
return await db('users').update(id, { login, password: passwordHash });
},
async create({login, password}) {
const passwordHash = await common.hash(password);
return await db('users').create({login, password: passwordHash});
},

async delete(id) {
return await db('users').delete(id);
},
async update(id, {login, password}) {
const passwordHash = await common.hash(password);
return await db('users').update(id, {login, password: passwordHash});
},

async find(mask) {
const sql = 'SELECT login from users where login like $1';
return await db('users').query(sql, [mask]);
},
});
async delete(id) {
return await db('users').delete(id);
},

async find(mask) {
const sql = 'SELECT login from users where login like $1';
return await db('users').query(sql, [mask]);
},
};
10 changes: 10 additions & 0 deletions JavaScript/9-logger/body.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict';

const receiveArgs = async (req) => {
const buffers = [];
for await (const chunk of req) buffers.push(chunk);
const data = Buffer.concat(buffers).toString();
return JSON.parse(data);
};

module.exports = receiveArgs;
27 changes: 27 additions & 0 deletions JavaScript/9-logger/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
module.exports = {
apiServer: {
/**
* @type {string} 'http' | 'ws'
*/
transport: 'http',
port: 3000,
},
staticServer: {
port: 8000,
},
crypto: {
saltLenByte: 16,
scryptLenByte: 64,
},
database: {
host: 'localhost',
port: 5432,
database: 'metatech',
user: 'admin',
password: 'admin',
},
/**
* @type {string} 'pino' | 'meta'
*/
logger: 'pino'
};
95 changes: 48 additions & 47 deletions JavaScript/9-logger/db.js
Original file line number Diff line number Diff line change
@@ -1,59 +1,60 @@
'use strict';

const pg = require('pg');
const config = require('./config');

const pool = new pg.Pool({
host: '127.0.0.1',
port: 5432,
database: 'example',
user: 'marcus',
password: 'marcus',
host: config.database.host,
port: config.database.port,
database: config.database.database,
user: config.database.user,
password: config.database.password,
});

module.exports = (table) => ({
async query(sql, args) {
return await pool.query(sql, args);
},
async query(sql, args) {
return await pool.query(sql, args);
},

async read(id, fields = ['*']) {
const names = fields.join(', ');
const sql = `SELECT ${names} FROM ${table}`;
if (!id) return pool.query(sql);
return await pool.query(`${sql} WHERE id = $1`, [id]);
},
async read(id, fields = ['*']) {
const names = fields.join(', ');
const sql = `SELECT ${names} FROM ${table}`;
if (!id) return pool.query(sql);
return await pool.query(`${sql} WHERE id = $1`, [id]);
},

async create({ ...record }) {
const keys = Object.keys(record);
const nums = new Array(keys.length);
const data = new Array(keys.length);
let i = 0;
for (const key of keys) {
data[i] = record[key];
nums[i] = `$${++i}`;
}
const fields = '"' + keys.join('", "') + '"';
const params = nums.join(', ');
const sql = `INSERT INTO "${table}" (${fields}) VALUES (${params})`;
return await pool.query(sql, data);
},
async create({ ...record }) {
const keys = Object.keys(record);
const nums = new Array(keys.length);
const data = new Array(keys.length);
let i = 0;
for (const key of keys) {
data[i] = record[key];
nums[i] = `$${++i}`;
}
const fields = '"' + keys.join('", "') + '"';
const params = nums.join(', ');
const sql = `INSERT INTO "${table}" (${fields}) VALUES (${params}) RETURNING id`;
return await pool.query(sql, data);
},

async update(id, { ...record }) {
const keys = Object.keys(record);
const updates = new Array(keys.length);
const data = new Array(keys.length);
let i = 0;
for (const key of keys) {
data[i] = record[key];
updates[i] = `${key} = $${++i}`;
}
const delta = updates.join(', ');
const sql = `UPDATE ${table} SET ${delta} WHERE id = $${++i}`;
data.push(id);
return await pool.query(sql, data);
},
async update(id, { ...record }) {
const keys = Object.keys(record);
const updates = new Array(keys.length);
const data = new Array(keys.length);
let i = 0;
for (const key of keys) {
data[i] = record[key];
updates[i] = `${key} = $${++i}`;
}
const delta = updates.join(', ');
const sql = `UPDATE ${table} SET ${delta} WHERE id = $${++i}`;
data.push(id);
return await pool.query(sql, data);
},

async delete(id) {
const sql = `DELETE FROM ${table} WHERE id = $1`;
return await pool.query(sql, [id]);
},
});
async delete(id) {
const sql = `DELETE FROM ${table} WHERE id = $1`;
return await pool.query(sql, [id]);
},
});
15 changes: 7 additions & 8 deletions JavaScript/9-logger/hash.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
'use strict';

const crypto = require('node:crypto');
const scrypt = require('node:util').promisify(crypto.scrypt);

const hash = (password) => new Promise((resolve, reject) => {
const salt = crypto.randomBytes(16).toString('base64');
crypto.scrypt(password, salt, 64, (err, result) => {
if (err) reject(err);
resolve(salt + ':' + result.toString('base64'));
});
});
const hash = async (password) => {
const salt = crypto.randomBytes(16).toString('base64');
const result = await scrypt(password, salt, 64);
return salt + ':' + result.toString('base64');
};

module.exports = hash;
module.exports = hash;
44 changes: 22 additions & 22 deletions JavaScript/9-logger/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,29 @@
const http = require('node:http');

const receiveArgs = async (req) => {
const buffers = [];
for await (const chunk of req) buffers.push(chunk);
const data = Buffer.concat(buffers).toString();
return JSON.parse(data);
const buffers = [];
for await (const chunk of req) buffers.push(chunk);
const data = Buffer.concat(buffers).toString();
return JSON.parse(data);
};

module.exports = (routing, port) => {
http.createServer(async (req, res) => {
const { url, socket } = req;
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 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.rows));
}).listen(port);
http.createServer(async (req, res) => {
const { url, socket } = req;
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 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.rows));
}).listen(port);

console.log(`API on port ${port}`);
};
console.log(`Listen on port ${port}`);
};
14 changes: 7 additions & 7 deletions JavaScript/9-logger/load.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ const vm = require('node:vm');
const RUN_OPTIONS = { timeout: 5000, displayErrors: false };

module.exports = async (filePath, sandbox) => {
const src = await fs.readFile(filePath, 'utf8');
const code = `'use strict';\n${src}`;
const script = new vm.Script(code);
const context = vm.createContext(Object.freeze({ ...sandbox }));
const exported = script.runInContext(context, RUN_OPTIONS);
return exported;
};
const src = await fs.readFile(filePath, 'utf8');
const code = `'use strict';\n${src}`;
const script = new vm.Script(code);
const context = vm.createContext(Object.freeze({ ...sandbox }));
const exported = script.runInContext(context, RUN_OPTIONS);
return exported;
};
1 change: 1 addition & 0 deletions JavaScript/9-logger/logger.di.container.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = Object.freeze(require('./logger'));
Loading

0 comments on commit 850c07f

Please sign in to comment.