Skip to content
This repository has been archived by the owner on Sep 26, 2023. It is now read-only.

Commit

Permalink
Return author on GET book endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
niclim committed Jun 29, 2023
1 parent 3d5c262 commit c4830d7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
16 changes: 13 additions & 3 deletions src/routes/books/get.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { FastifyInstance } from "fastify";
import { Type, Static } from "@sinclair/typebox";

import * as Authors from "../../services/authors";
import * as Books from "../../services/books";
import * as Errors from "../../services/errors";

Expand All @@ -9,24 +10,33 @@ const GetBookParams = Type.Object({
});
type GetBookParams = Static<typeof GetBookParams>;

const GetBookResponse = Type.Composite([
Books.BookResponse,
Type.Object({
author: Type.Optional(Authors.AuthorResponse),
}),
]);
type GetBookResponse = Static<typeof GetBookResponse>;

export const registerGetBook = (app: FastifyInstance) => {
app.get<{
Params: GetBookParams;
Reply: Books.BookResponse | Errors.NotFound;
Reply: GetBookResponse | Errors.NotFound;
}>(
`/books/:bookId`,
{
schema: {
params: GetBookParams,
response: { 200: Books.BookResponse, 404: Errors.NotFound },
response: { 200: GetBookResponse, 404: Errors.NotFound },
},
},
(request, reply) => {
const book = Books.get(request.params.bookId);
if (!book) {
reply.code(404).send({ message: "Not Found" });
} else {
reply.code(200).send(book);
const author = Authors.get(book.author_id) ?? undefined;
reply.code(200).send({ ...book, author: author });
}
}
);
Expand Down
16 changes: 14 additions & 2 deletions src/routes/books/getMany.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import { FastifyInstance } from "fastify";
import { Type, Static } from "@sinclair/typebox";

import * as Authors from "../../services/authors";
import * as Books from "../../services/books";
import { PaginatedTypeBox } from "../../services/paginated";

const GetBooksResponse = PaginatedTypeBox(Books.BookResponse);
const BookWithAuthor = Type.Composite([
Books.BookResponse,
Type.Object({
author: Type.Optional(Authors.AuthorResponse),
}),
]);
type BookWithAuthor = Static<typeof BookWithAuthor>;

const GetBooksResponse = PaginatedTypeBox(BookWithAuthor);
type GetBooksResponse = Static<typeof GetBooksResponse>;

const GetBooksQuery = Type.Object({
Expand Down Expand Up @@ -41,7 +50,10 @@ export const registerGetBooks = (app: FastifyInstance) => {
const books = Books.getMany(sort);
reply.code(200).send({
has_more_data: false,
data: books,
data: books.map((b) => ({
...b,
author: Authors.get(b.author_id) ?? undefined,
})),
next: null,
});
}
Expand Down

0 comments on commit c4830d7

Please sign in to comment.