REST Controllers
This section will focus on getting our REST controllers set up to deal with our HTTP endpoint, we shall also cover a basic HTML page to interact with our API and then also host that.
Creating our HTTP endpoint.
Let's create the todo controller.
Each HTTP controller route the data is automatically converted into a Response object for you, we use the
toResponse
utility method. For customisation simply return your own Response object.
import { Controller, Get, Post, Patch, Put, Delete, Body, Query } from '@sodacore/core';
import { Inject } from '@sodacore/di';
import { PrismaClient } from '../generated/prisma';
@Controller('/api/todo')
export class TodoController {
@Inject() private prisma!: PrismaClient;
@Get('/')
public async list() {
const todos = await this.prisma.Todos.findMany();
return todos;
}
@Get('/:id')
public async get(@Query('id') id: string) {
const todo = await this.prisma.Todos.findUnique({
where: { id: parseInt(id) },
});
if (!todo) throw new Error('Todo not found');
return todo;
}
@Post('/')
public async create(@Body() body: { title: string }) {
const todo = await this.prisma.Todos.create({
data: {
title: body.title,
},
});
return todo;
}
@Put('/:id')
public async update(@Query('id') id: string, @Body() body: { title?: string; completed?: boolean }) {
const todo = await this.prisma.Todos.update({
where: { id: parseInt(id) },
data: {
title: body.title,
completed: body.completed,
},
});
return todo;
}
@Patch('/:id')
public async patch(@Query('id') id: string, @Body() body: { title?: string; completed?: boolean }) {
const todo = await this.prisma.Todos.update({
where: { id: parseInt(id) },
data: {
...body,
},
});
return todo;
}
@Delete('/:id')
public async delete(@Query('id') id: string) {
const todo = await this.prisma.Todos.delete({
where: { id: parseInt(id) },
});
return todo;
}
}
Now that we have our rest controller, we can see we have defined a series of methods to handle our HTTP requests, and we have used the Prisma integration to apply our CRUD operations to the database.
Now if you were to run your application using bun dev
, you can access your API at http://localhost:3000/api/todo
, which should return an empty array as we have no data in our database yet.
Creating a basic HTML page.
We won't focus on any kind of API