Skip to content

Commit

Permalink
Merge 497efed into 1eb60a4
Browse files Browse the repository at this point in the history
  • Loading branch information
MrOrz committed Jul 4, 2021
2 parents 1eb60a4 + 497efed commit 7d54e2f
Show file tree
Hide file tree
Showing 7 changed files with 149 additions and 17 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`appVariable [model] sets valid value to DB 1`] = `
Object {
"_id": "foo",
"value": "123456",
}
`;
52 changes: 52 additions & 0 deletions src/database/models/__tests__/appVariable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import Client from '../../mongoClient';
import AppVariable from '../appVariable';

describe('appVariable', () => {
beforeAll(async () => {
if (await AppVariable.collectionExists()) {
await (await AppVariable.client).drop();
}
});

afterAll(async () => {
await (await Client.getInstance()).close();
});

it('[schema] should pass', async () => {
const data = {
_id: 'foo',
value: 'some string',
};
const { valid } = AppVariable.validator(data);
expect(valid).toBe(true);
});

it('[model] sets valid value to DB', async () => {
await AppVariable.set('foo', 123456);

const data = (await AppVariable.find({ _id: 'foo' }))[0];
expect(data).toMatchSnapshot();

const { valid } = AppVariable.validator(data);
expect(valid).toBe(true);
});

it('[model] gets undefined for variables not set yet', async () => {
const value = await AppVariable.get('notExist');
expect(value).toBe(undefined);
});

it('[model] gets setted primitive and objects', async () => {
await AppVariable.set('num', 123456);
expect(await AppVariable.get('num')).toBe(123456);

await AppVariable.set('null', null);
expect(await AppVariable.get('null')).toBe(null);

await AppVariable.set('str', '123');
expect(await AppVariable.get('str')).toBe('123');

await AppVariable.set('obj', { foo: 123 });
expect(await AppVariable.get('obj')).toEqual({ foo: 123 });
});
});
35 changes: 35 additions & 0 deletions src/database/models/appVariable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import Base from './base';

class AppVariable extends Base {
static get collection() {
return 'appVariable';
}

/**
* @param {string} varName - the name of app variable to read
* @returns {Promise<any>} - variable value
*/
static async get(varName) {
const result = await this.find({ _id: varName });
if (result.length === 0) {
// Resolves to undefined if varName is not set previously
return;
}

return JSON.parse(result[0].value);
}

/**
*
* @param {string} varName - the name of app variable to write
* @param {any} value
* @returns {Promise<AppVariable>}
*/
static async set(varName, value) {
const valueStr = JSON.stringify(value);

return this.findOneAndUpdate({ _id: varName }, { value: valueStr });
}
}

export default AppVariable;
18 changes: 18 additions & 0 deletions src/database/models/appVariable.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "cofacts/schemas/appVariable",
"$comment": "design document https://g0v.hackmd.io/eIeU2g86Tfu5VnLazNfUvQ",
"description": "A representation of an AppVariable",
"title": "AppVariable",
"type": "object",

"properties": {
"_id": {
"type": "string"
},
"value": {
"type": "string"
}
},
"required": [ "value" ]
}
2 changes: 2 additions & 0 deletions src/database/models/schemaValidator.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const ajv = new Ajv();
const SCHEMAS = {
userArticleLink: require('./userArticleLink.json'),
userSettings: require('./userSettings.json'),
appVariable: require('./appVariable.json'),
};

const ClassTable = {
Expand All @@ -31,4 +32,5 @@ export function compile(schemaName) {
export const validators = {
userArticleLink: compile('userArticleLink'),
userSettings: compile('userSettings'),
appVariable: compile('appVariable'),
};
26 changes: 21 additions & 5 deletions src/scripts/__tests__/scanRepliesAndNotify.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,33 @@
jest.mock('src/lib/redisClient');
jest.mock('./lib');

import Client from 'src/database/mongoClient';
import MockDate from 'mockdate';
import scanRepliesAndNotify from '../scanRepliesAndNotify';
import AppVariable from 'src/database/models/appVariable';
import lib from '../lib';
import redis from 'src/lib/redisClient';

beforeEach(async () => {
if (await AppVariable.collectionExists()) {
await (await AppVariable.client).drop();
}
});

afterAll(async () => {
await (await Client.getInstance()).close();
});

it('scan replies and notify', async () => {
redis.set = jest.fn();
redis.quit = jest.fn();
lib.getNotificationList = jest.fn().mockImplementationOnce(() => {});
lib.sendNotification = jest.fn();
MockDate.set(612921600000);

await scanRepliesAndNotify();

expect(lib.getNotificationList).toHaveBeenCalledTimes(1);
expect(lib.sendNotification).toHaveBeenCalledTimes(1);

// Time should be 12 hours before MockDate
// 12 hour is the default REVIEW_REPLY_BUFFER
expect(await AppVariable.get('lastScannedAt')).toMatchInlineSnapshot(
`"1989-06-03T12:00:00.000Z"`
);
});
25 changes: 13 additions & 12 deletions src/scripts/scanRepliesAndNotify.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import lib from './lib';
import redis from 'src/lib/redisClient';
import AppVariable from 'src/database/models/appVariable';
import rollbar from 'src/lib/rollbar';
import addTime from 'date-fns/add';
import Client from 'src/database/mongoClient';

export default async function scanRepliesAndNotify() {
const timeOffset = JSON.parse(process.env.REVIEW_REPLY_BUFFER) || {};
const lastScannedAt =
(await redis.get('lastScannedAt')) ||
(await AppVariable.get('lastScannedAt')) ||
addTime(new Date(), { days: -90 }).toISOString();

console.log('[notify] lastScannedAt:' + lastScannedAt);
Expand All @@ -17,17 +17,18 @@ export default async function scanRepliesAndNotify() {
nowWithOffset
);
await lib.sendNotification(notificationList);
await redis.set('lastScannedAt', nowWithOffset);

// disconnect redis and mongodb
await redis.quit();
await (await Client.getInstance()).close();
await AppVariable.set('lastScannedAt', nowWithOffset);
}

if (require.main === module) {
scanRepliesAndNotify().catch(e => {
console.error(e);
rollbar.error(e);
process.exit(1);
});
scanRepliesAndNotify()
.catch(e => {
console.error(e);
rollbar.error(e);
process.exit(1);
})
.then(async () => {
// disconnect mongodb
await (await Client.getInstance()).close();
});
}

0 comments on commit 7d54e2f

Please sign in to comment.