diff --git a/src/routes/authors/getMany.ts b/src/routes/authors/getMany.ts index ed38caf..6921194 100644 --- a/src/routes/authors/getMany.ts +++ b/src/routes/authors/getMany.ts @@ -1,5 +1,5 @@ import { FastifyInstance } from "fastify"; -import { Static } from "@sinclair/typebox"; +import { Type, Static } from "@sinclair/typebox"; import * as Authors from "../../services/authors"; import { PaginatedTypeBox } from "../../services/paginated"; @@ -7,18 +7,38 @@ import { PaginatedTypeBox } from "../../services/paginated"; const GetAuthorsResponse = PaginatedTypeBox(Authors.AuthorResponse); type GetAuthorsResponse = Static; +const GetAuthorsQuery = Type.Object({ + sortOrder: Type.Optional( + Type.String({ + enum: ["asc", "desc"], + }) + ), + sortKey: Type.Optional( + Type.String({ + enum: ["name", "created_at", "updated_at"], + }) + ), +}); +type GetAuthorsQuery = Static; + export const registerGetAuthors = (app: FastifyInstance) => { app.get<{ + Querystring: GetAuthorsQuery; Reply: GetAuthorsResponse; }>( `/authors`, { schema: { + querystring: GetAuthorsQuery, response: { 200: GetAuthorsResponse }, }, }, (request, reply) => { - const authors = Authors.getMany(); + const sort = { + order: request.query.sortOrder ?? "asc", + key: request.query.sortKey ?? "name", + } as Parameters["0"]; + const authors = Authors.getMany(sort); reply.code(200).send({ has_more_data: false, data: authors, diff --git a/src/services/authors.ts b/src/services/authors.ts index 5a608fa..38fee53 100644 --- a/src/services/authors.ts +++ b/src/services/authors.ts @@ -59,8 +59,18 @@ export function update( return author ?? null; } -export function getMany(): AuthorResponse[] { - return [...authorDatabase.values()]; +export function getMany(sort: { + key: "name" | "created_at" | "updated_at"; + order: "asc" | "desc"; +}): AuthorResponse[] { + return [...authorDatabase.values()].sort((a, b) => { + const comparison = + sort.key === "name" + ? a.name.localeCompare(b.name) + : new Date(a[sort.key]).getTime() - new Date(b[sort.key]).getTime(); + const order = sort.order === "asc" ? 1 : -1; + return comparison * order; + }); } export function get(id: string): AuthorResponse | null {