Rework edit history service, add unit tests

This commit is contained in:
Maciej Ziarkowski 2020-01-27 01:08:32 +00:00
parent e682cfa074
commit 4ff64cda79
2 changed files with 65 additions and 14 deletions

View File

@ -0,0 +1,43 @@
import { mocked } from 'ts-jest/utils';
import { EditHistoryEntry } from '../../../frontend/models/edit-history-entry';
import * as editHistoryData from '../../dataAccess/editHistory'; // manually mocked
import { getGlobalEditHistory } from '../editHistory';
jest.mock('../../dataAccess/editHistory');
const mockedEditHistoryData = editHistoryData as typeof import('../../dataAccess/__mocks__/editHistory');
describe('getGlobalEditHistory()', () => {
mockedEditHistoryData.__setHistory(
[...Array(20).keys()].map<EditHistoryEntry>(i => ({
revision_id: (100 + i) + '',
revision_timestamp: new Date(2019, 10, 1, 17, 20 + i).toISOString(),
username: 'testuser',
building_id: 1234567,
forward_patch: {},
reverse_patch: {}
}))
);
describe('without before/after parameters', () => {
it.each(
[
[0, []],
[3, ['119', '118', '117']],
[6, ['119', '118', '117', '116', '115', '114']]
]
)('should return the N latest records in descending order', async (count: number, ids: string[]) => {
const historyResult = await getGlobalEditHistory(null, null, count);
expect(historyResult.history.map(h => h.revision_id)).toEqual(ids);
});
});
describe('with after ID parameter', () => {
});
describe('with before ID parameter', () => {
});
});

View File

@ -1,20 +1,28 @@
import db from '../../db'; import { EditHistoryEntry } from '../../frontend/models/edit-history-entry';
import { getHistoryAfterId, getHistoryBeforeId, getIdNewerThan, getIdOlderThan, getLatestHistory } from '../dataAccess/editHistory';
async function getGlobalEditHistory() { async function getGlobalEditHistory(beforeId?: string, afterId?: string, count: number = 100) {
try { // limited set of records. Expected to be already ordered from newest to oldest
return await db.manyOrNone( let editHistoryRecords: EditHistoryEntry[];
`SELECT log_id as revision_id, forward_patch, reverse_patch, date_trunc('minute', log_timestamp) as revision_timestamp, username, building_id
FROM logs, users if(afterId != undefined) {
WHERE logs.user_id = users.user_id editHistoryRecords = await getHistoryAfterId(afterId, count);
AND log_timestamp >= now() - interval '7 days' } else if (beforeId != undefined) {
ORDER BY log_timestamp DESC` editHistoryRecords = await getHistoryBeforeId(beforeId, count);
); } else {
} catch (error) { editHistoryRecords = await getLatestHistory(count);
console.error(error);
return [];
}
} }
const newer = getIdNewerThan(editHistoryRecords[0]?.revision_id);
const older = getIdOlderThan(editHistoryRecords[editHistoryRecords.length-1]?.revision_id);
return {
history: editHistoryRecords,
paging: {
has_newer: newer != undefined,
has_older: older != undefined
}
};
}
export { export {
getGlobalEditHistory getGlobalEditHistory