Skip to content
This repository was archived by the owner on Sep 26, 2023. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions src/routes/authors/getMany.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,44 @@
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";

const GetAuthorsResponse = PaginatedTypeBox(Authors.AuthorResponse);
type GetAuthorsResponse = Static<typeof GetAuthorsResponse>;

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<typeof GetAuthorsQuery>;

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<typeof Authors.getMany>["0"];
const authors = Authors.getMany(sort);
reply.code(200).send({
has_more_data: false,
data: authors,
Expand Down
14 changes: 12 additions & 2 deletions src/services/authors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down