Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions application/api/auth/provider.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,28 @@

async saveSession(token, data) {
console.log({ saveSession: { token, data } });
const payload = { data: JSON.stringify(data) };
try {
await db.pg.update('Session', { data: JSON.stringify(data) }, { token });
await db.pg.update('Session', payload, { token });
} catch (error) {
console.error(error);
}
},

async createSession(token, data, fields = {}) {
const record = { token, data: JSON.stringify(data), ...fields };
const record = {
token,
data: JSON.stringify(data),
...fields,
};
console.log({ createSession: record });
return db.pg.insert('Session', record);
},

async readSession(token) {
const record = await db.pg.row('Session', ['data'], { token });
console.log({ readSession: { token, record } });
if (record && record.data) return record.data;
if (record?.data) return record.data;
return null;
},

Expand Down
3 changes: 2 additions & 1 deletion application/api/auth/restore.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
const restored = context.client.restoreSession(token);
if (restored) return { status: 'logged' };
const data = await api.auth.provider.readSession(token);
return { status: data ? 'logged' : 'not logged' };
const status = data ? 'logged' : 'not logged';
return { status };
},
});
2 changes: 1 addition & 1 deletion application/api/auth/signin.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
if (!valid) throw new Error('Incorrect login or password');
console.log(`Logged user: ${login}`);
const token = api.auth.provider.generateToken();
const data = { accountId: user.accountId };
const data = { accountId };
context.client.startSession(token, data);
const { ip } = context.client;
await api.auth.provider.createSession(token, data, { ip, accountId });
Expand Down
1 change: 0 additions & 1 deletion application/api/console/content.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
access: 'public',

async method({ name }) {
// Try type: new api.console.content.CustomError('EPARSE');
const filePath = `/content/${name}.md`;
const file = application.resources.get(filePath);
if (!file) return new Error('Content is not found');
Expand Down
6 changes: 3 additions & 3 deletions application/api/example/counter.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
async () => {
if (!context.session.counter) context.session.counter = 1;
else context.session.counter++;
return { result: context.session.counter };
const { session = { counter: 0 } } = context;
session.counter++;
return { result: session.counter };
};
3 changes: 2 additions & 1 deletion application/api/example/getClientInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
const { uuid, session, client } = context;
const { ip } = client;
const { token, accountId } = session;
return { result: { ip, token, accountId, uuid } };
const result = { ip, token, accountId, uuid };
return { result };
},
});
2 changes: 1 addition & 1 deletion application/api/example/remoteMethod.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
({
access: 'public',
method: async ({ ...args }) => {
method: async (args) => {
console.debug({ remoteMethod: args });
return { result: 'success' };
},
Expand Down
3 changes: 2 additions & 1 deletion application/api/example/subscribe.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
access: 'public',

method: async () => {
const { interval } = config.resmon;
setInterval(async () => {
const stats = await lib.resmon.getStatistics();
context.client.emit('example/resmon', stats);
}, config.resmon.interval);
}, interval);
return { subscribed: 'resmon' };
},
});
3 changes: 2 additions & 1 deletion application/api/example/uploadFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ async ({ name, data }) => {
const buffer = Buffer.from(data, 'base64');
const tmpPath = 'application/tmp';
const filePath = node.path.join(tmpPath, name);
if (filePath.startsWith(tmpPath)) {
const isInsideTmp = filePath.startsWith(tmpPath);
if (isInsideTmp) {
await node.fsp.writeFile(filePath, buffer);
}
return { uploaded: data.length };
Expand Down
8 changes: 5 additions & 3 deletions application/api/example/wait.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
async ({ delay }) =>
new Promise((resolve) => {
setTimeout(resolve, delay, 'done');
async ({ delay }) => {
await new Promise((resolve) => {
setTimeout(resolve, delay);
});
return 'done';
};
4 changes: 0 additions & 4 deletions application/api/files/download.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
async ({ name, type }) => {
const filePath = `./application/resources/${name}`;
// Create nodejs readable stream to read a file
const readable = node.fs.createReadStream(filePath);
// Get file size
const { size } = await node.fsp.stat(filePath);
// Create metacom writable stream
const writable = context.client.createStream(name, size);
// Pipe nodejs readable to metacom writable
readable.pipe(writable);
return { streamId: writable.id, type };
};
3 changes: 0 additions & 3 deletions application/api/files/upload.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
async ({ streamId, name }) => {
const filePath = `./application/resources/${name}`;
// Get incoming stream by streamId sent from client
const readable = context.client.getStream(streamId);
// Create nodejs stream to write file on server
const writable = node.fs.createWriteStream(filePath);
// Pipe metacom readable to nodejs writable
readable.pipe(writable);
return { result: 'Stream initialized' };
};
20 changes: 10 additions & 10 deletions application/bus/worldTime/currentTime.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@

returns: {
abbreviation: 'string',
[`client_ip`]: 'string',
client_ip: 'string',
datetime: 'string',
[`day_of_week`]: 'number',
[`day_of_year`]: 'number',
day_of_week: 'number',
day_of_year: 'number',
dst: 'boolean',
[`dst_from`]: 'string',
[`dst_offset`]: 'number',
[`dst_until`]: 'string',
[`raw_offset`]: 'number',
dst_from: 'string',
dst_offset: 'number',
dst_until: 'string',
raw_offset: 'number',
timezone: 'string',
unixtime: 'number',
[`utc_datetime`]: 'string',
[`utc_offset`]: 'string',
[`week_number`]: 'number',
utc_datetime: 'string',
utc_offset: 'string',
week_number: 'number',
},
});
5 changes: 2 additions & 3 deletions application/db/pg/start.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
async () => {
if (application.worker.id === 'W1') {
console.debug('Connect to pg');
}
const isPrimary = application.worker.id === 'W1';
if (isPrimary) console.debug('Connect to pg');
const options = { ...config.database, console };
db.pg = new metarhia.metasql.Database(options);
};
14 changes: 7 additions & 7 deletions application/db/redis/start.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
async () => {
if (application.worker.id === 'W1') {
const isPrimary = application.worker.id === 'W1';
if (isPrimary) {
console.debug('Connect to redis');
}
const client = npm.redis.createClient(config.redis);
db.redis.client = client;
client.on('error', async (error) => {
if (application.worker.id === 'W1') {
console.warn('No redis service detected, so quit client');
const err = new Error('No redis', { cause: error });
console.error(err);
await client.disconnect();
}
if (!isPrimary) return;
console.warn('No redis service detected, so quit client');
const err = new Error('No redis', { cause: error });
console.error(err);
await client.disconnect();
});
await client.connect();
};
6 changes: 3 additions & 3 deletions application/domain/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
rooms: new Map(),

getRoom(name) {
let room = domain.chat.rooms.get(name);
if (room) return room;
room = new Set();
const existing = domain.chat.rooms.get(name);
if (existing) return existing;
const room = new Set();
domain.chat.rooms.set(name, room);
return room;
},
Expand Down
10 changes: 4 additions & 6 deletions application/domain/tests/api.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
({
async cases(t, metacom) {
if (t) return;
const res = await metacom.api.auth.signin({
login: 'marcus',
password: 'marcus',
});
const credentials = { login: 'marcus', password: 'marcus' };
const res = await metacom.api.auth.signin(credentials);
node.assert.strictEqual(res.status, 'logged');
node.assert.strictEqual(typeof res.token, 'string');

await t.test(`Call example.add({ a, b })`, async () => {
const res = await metacom.api.example.add({ a: 10, b: 20 });
node.assert.strictEqual(res, 30);
const sum = await metacom.api.example.add({ a: 10, b: 20 });
node.assert.strictEqual(sum, 30);
});
},
});
2 changes: 1 addition & 1 deletion application/domain/tests/static.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

const tasks = [
{ url: '/', size: 2099 },
{ url: '/console.js', size: 14360 },
{ url: '/console.js', size: 13862 },
{ url: '/unknown', status: 404, size: 113 },
{ url: '/unknown.png', status: 404, size: 113 },
{ url: '/unknown/unknown', status: 404 },
Expand Down
3 changes: 2 additions & 1 deletion application/domain/time/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ async () => {
area: 'Europe',
location: 'Rome',
});
console.log(`${time.timezone} - ${time.datetime}`);
const { timezone, datetime } = time;
console.log(`${timezone} - ${datetime}`);
} catch {
console.log('Can not access time server');
}
Expand Down
6 changes: 3 additions & 3 deletions application/lib/example/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
},

get({ key }) {
const res = this.values.get(key);
console.debug({ get: key, return: res });
return res;
const value = this.values.get(key);
console.debug({ get: key, return: value });
return value;
},
});
10 changes: 4 additions & 6 deletions application/lib/example/storage/set.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@

method({ key, val }) {
console.log({ key, val });
if (val) {
return this.values.set(key, val);
}
const res = this.values.get(key);
console.log({ return: { res } });
return res;
if (val) return this.values.set(key, val);
const value = this.values.get(key);
console.log({ return: { res: value } });
return value;
},
});
6 changes: 3 additions & 3 deletions application/lib/resmon/getStatistics.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
async () => {
const { heapTotal, heapUsed, external } = process.memoryUsage();
const hs = node.v8.getHeapStatistics();
const contexts = hs.number_of_native_contexts;
const detached = hs.number_of_detached_contexts;
const heapStats = node.v8.getHeapStatistics();
const contexts = heapStats.number_of_native_contexts;
const detached = heapStats.number_of_detached_contexts;
return { heapTotal, heapUsed, external, contexts, detached };
};
5 changes: 3 additions & 2 deletions application/lib/task1/start.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
async () => {
if (!config.examples.scheduler) return;
if (application.worker.id !== 'W1') return;
const res = await application.scheduler.add({
const task = {
name: 'name',
every: 'Oct 19th 10s',
args: { i: 2 },
run: 'lib.task1.f1',
});
};
const res = await application.scheduler.add(task);
console.log('Add task', res);
};
9 changes: 5 additions & 4 deletions application/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@

bytesToSize(bytes) {
if (bytes === 0) return '0';
const exp = Math.floor(Math.log(bytes) / Math.log(1000));
const size = bytes / 1000 ** exp;
const short = Math.round(size, 2);
const base = 1000;
const exp = Math.floor(Math.log(bytes) / Math.log(base));
const size = bytes / base ** exp;
const short = Math.round(size);
const unit = this.UNITS[exp];
return short + unit;
return `${short}${unit}`;
},

UNIT_SIZES: {
Expand Down
Loading
Loading