Skip to content

Commit

Permalink
Add update and delete for books (#1)
Browse files Browse the repository at this point in the history
* add delete for book

* add update for book
  • Loading branch information
birk-bre authored Feb 6, 2024
1 parent 2541f0b commit f90c89a
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,56 @@ const app = new Elysia()
),
},
)
.delete('book/:isbn', async ({ params: { isbn }, set }) => {
const client = getClient()

if (await client.query('SELECT * FROM books where isbn = $1', [isbn]).then((it) => it.rows.length === 0)) {
set.status = 'Not Found'
return null
}

await client.query('DELETE FROM books WHERE isbn = $1', [isbn])

console.info(`Deleted book with ISBN ${isbn}`)

return { isbn }
})
.put(
'book/:isbn',
async ({ params: { isbn }, body, set }) => {
const client = getClient()

const isbnRegex = /^(?=(?:\D*\d){10}(?:(?:\D*\d){3})?$)[\d-]+$/
if (!isbnRegex.test(body.isbn)) {
set.status = 'Bad Request'
return null
}

const result = await client.query<Pick<DbBook, 'isbn' | 'published_date' | 'title'>>(
'UPDATE books SET isbn = $1, title = $2, published_date = $3 WHERE isbn = $4 RETURNING isbn, title, published_date',
[body.isbn, body.title, body.published_date, isbn],
)

if (result.rows.length === 0) return null

const updatedBook = result.rows[0]
return updatedBook
},
{
response: t.Nullable(
t.Object({
isbn: t.String(),
title: t.String(),
published_date: t.Date({ description: 'ISO8601 Date' }),
}),
),
body: t.Object({
isbn: t.String(),
title: t.String(),
published_date: t.String({ description: 'ISO8601 Date' }),
}),
},
)
.post('dev/re-seed', async () => {
const client = getClient()
await client.query('BEGIN')
Expand Down

0 comments on commit f90c89a

Please sign in to comment.