Skip to content

Commit 989479d

Browse files
author
Ido Shamun
committed
feat: return the latest notification on empty result
1 parent 8f4b19a commit 989479d

File tree

4 files changed

+31
-4
lines changed

4 files changed

+31
-4
lines changed

src/models/notification.js

+7-2
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,16 @@ const table = 'notifications';
44

55
const get = (since) => {
66
const select = db.select().from(table);
7-
const query = since ? select.where('timestamp', '>=', since) : select;
7+
const query = since ? select.where('timestamp', '>', since) : select;
88
return query.orderBy('timestamp', 'ASC').limit(5).map(toCamelCase);
99
};
1010

11+
const getLatest = () =>
12+
db.select().from(table).orderBy('timestamp', 'DESC').limit(1)
13+
.map(toCamelCase)
14+
.then(res => (res.length ? res[0] : null));
15+
1116
const add = obj => db.insert(toSnakeCase(obj)).into(table)
1217
.then(() => obj);
1318

14-
export default { get, add };
19+
export default { get, getLatest, add };

src/routes/notifications.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,16 @@ router.get(
1616
},
1717
}),
1818
async (ctx) => {
19-
const model = await notification.get(ctx.request.query.since);
19+
const latestPromise = notification.getLatest();
20+
const since = await notification.get(ctx.request.query.since);
2021

2122
ctx.status = 200;
22-
ctx.body = model;
23+
if (since.length) {
24+
ctx.body = since;
25+
} else {
26+
const latest = await latestPromise;
27+
ctx.body = latest ? [latest] : [];
28+
}
2329
},
2430
);
2531

test/integration/models/notification.js

+7
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,11 @@ describe('notification model', () => {
2828
const model = await notification.get(new Date(2017, 10, 21, 15, 58, 0));
2929
expect(model).to.deep.equal(fixture.slice(2, 7));
3030
});
31+
32+
it('should fetch latest notification', async () => {
33+
await Promise.all(fixture.map(n => notification.add(n)));
34+
35+
const model = await notification.getLatest();
36+
expect(model).to.deep.equal(fixture[fixture.length - 1]);
37+
});
3138
});

test/integration/routes/notifications.js

+9
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,13 @@ describe('notifications routes', () => {
5353

5454
expect(body).to.deep.equal(fixture.slice(2, 7).map(mapDate));
5555
});
56+
57+
it('should return latest notification', async () => {
58+
const { body } = await request
59+
.get('/v1/notifications')
60+
.query({ since: (new Date(2017, 10, 21, 19, 23, 5)).toISOString() })
61+
.expect(200);
62+
63+
expect(body).to.deep.equal(fixture.slice(6, 7).map(mapDate));
64+
});
5665
});

0 commit comments

Comments
 (0)