todo-backend: add ordering support

Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2021-03-10 21:46:47 +01:00
parent 3a7a803b0b
commit 803cc34d47
3 changed files with 72 additions and 2 deletions
@@ -78,8 +78,28 @@ export class TodoReaderService implements TodoService {
offset = totalCount - limit;
}
let items = todos.items;
const { orderBy } = req;
if (orderBy) {
const dir = orderBy.direction === 'asc' ? 1 : -1;
const field = orderBy.field;
items = items.slice().sort((item1, item2) => {
const field1 = item1[field];
const field2 = item2[field];
if (field1 && field2) {
return dir * field1?.localeCompare(field2, 'en-US');
} else if (field1 && !field2) {
return -1;
} else if (!field1 && field2) {
return 1;
}
return 0;
});
}
return {
items: todos.items.slice(offset, offset + limit),
items: items.slice(offset, offset + limit),
totalCount,
offset,
limit,
+47 -1
View File
@@ -20,6 +20,13 @@ import express from 'express';
import Router from 'express-promise-router';
import { TodoService } from './types';
const ALLOWED_ORDER_BY_FIELDS = [
'text',
'author',
'viewUrl',
'repoFilePath',
] as const;
export interface RouterOptions {
todoService: TodoService;
}
@@ -35,6 +42,11 @@ export async function createRouter(
router.get('/v1/todos', async (req, res) => {
const offset = parseIntegerParam(req.query.offset, 'offset query');
const limit = parseIntegerParam(req.query.limit, 'limit query');
const orderBy = parseOrderByParam(
req.query.orderBy,
'orderBy query',
ALLOWED_ORDER_BY_FIELDS,
);
const entityRef = req.query.entity;
if (entityRef && typeof entityRef !== 'string') {
@@ -49,7 +61,12 @@ export async function createRouter(
}
}
const todos = await todoService.listTodos({ entity, offset, limit });
const todos = await todoService.listTodos({
entity,
offset,
limit,
orderBy,
});
res.json(todos);
});
@@ -69,3 +86,32 @@ function parseIntegerParam(str: unknown, ctx: string): number | undefined {
}
return parsed;
}
function parseOrderByParam<T extends readonly string[]>(
str: unknown,
ctx: string,
allowedFields: T,
): { field: T[number]; direction: 'asc' | 'desc' } | undefined {
if (str === undefined) {
return undefined;
}
if (typeof str !== 'string') {
throw new InputError(`invalid ${ctx}, must be a string`);
}
const [field, direction] = str.split('=');
if (!field) {
throw new InputError(`invalid ${ctx}, field name is empty`);
}
if (direction !== 'asc' && direction !== 'desc') {
throw new InputError(
`invalid ${ctx}, order direction must be 'asc' or 'desc'`,
);
}
if (field && !allowedFields.includes(field)) {
throw new InputError(
`invalid orderBy query, must be one of ${allowedFields.join(', ')}`,
);
}
return { field, direction };
}
@@ -21,6 +21,10 @@ export type ListTodosRequest = {
entity?: EntityName;
offset?: number;
limit?: number;
orderBy?: {
field: 'text' | 'author' | 'viewUrl' | 'repoFilePath';
direction: 'asc' | 'desc';
};
};
export type ListTodosResponse = {