Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/added post put delete methods #23

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
90 changes: 89 additions & 1 deletion packages/backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ const TODOS = [
}
]

let nextTodoId = TODOS.length + 1

const app = new Elysia()
.get('/todos', () => TODOS)
.get(
'/todos/:id',
({ params, error }) => {
const todo = TODOS.find((todo) => todo.id === params.id)
const todo = TODOS.find((todo) => todo.id === Number(params.id))
if (!todo) {
return error(404)
}
Expand All @@ -32,11 +34,97 @@ const app = new Elysia()
})
}
)
.post(
'/todos',
({ body }) => {
const newTodo = {
id: nextTodoId++,
starred: false,
completed: false,
desc: body.desc
}
TODOS.push(newTodo)
return newTodo
},
{
body: t.Object({
desc: t.String()
})
}
)
.put(
'/todos/:id',
({ params, body, error }) => {
const todoIndex = TODOS.findIndex((todo) => todo.id === Number(params.id));
if (todoIndex === -1) {
return error(404);
}
TODOS[todoIndex] = { id: Number(params.id), ...body };
return TODOS[todoIndex];
},
{
params: t.Object({
id: t.Numeric()
}),
body: t.Object({
id: t.Optional(t.Numeric()),
starred: t.Boolean(),
completed: t.Boolean(),
desc: t.String()
})
}
)
.patch(
'/todos/:id',
({ params, body, error }) => {
const todo = TODOS.find((todo) => todo.id === Number(params.id));
if (!todo) {
return error(404);
}
if (body.starred !== undefined) {
todo.starred = body.starred;
}
if (body.completed !== undefined) {
todo.completed = body.completed;
}
if (body.desc !== undefined) {
todo.desc = body.desc;
}
return todo;
},
{
params: t.Object({
id: t.Numeric()
}),
body: t.Object({
starred: t.Optional(t.Boolean()),
completed: t.Optional(t.Boolean()),
desc: t.Optional(t.String())
})
}
)
.delete(
'/todos/:id',
({ params, error }) => {
const todoIndex = TODOS.findIndex((todo) => todo.id === Number(params.id))
if (todoIndex === -1) {
return error(404)
}
TODOS.splice(todoIndex, 1)
return { message: 'Todo item deleted successfully.' }
},
{
params: t.Object({
id: t.Numeric()
})
}
)
.listen(3000)

console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
)

/*
* GET /todos
* GET /todos/123421
Expand Down