This tutorial creates a small CRUD API under /api/todos. It demonstrates how the major Lanjit components work together in one runnable application.
What you will build
You will create a migration, define a Todo model, register list/create/update/delete routes, run the development server, and test the API with curl. Add authentication, authorization, and feature tests before adapting the example for production.
Examples
npm create lanjit@latest todo-app
cd todo-app
node artisan key:generate
node artisan make:migration create_todos_table
export async function up(schema) {
await schema.create('todos', (table) => {
table.id();
table.string('title');
table.boolean('completed').default(0);
});
}
export async function down(schema) {
await schema.dropIfExists('todos');
}
node artisan migrate
node artisan make:model Todo
import { Model } from '../../framework/Database/Model.js';
export class Todo extends Model {
static table = 'todos';
}
import { Todo } from '../app/Models/Todo.js';
export default function routes(Route) {
Route.get('/todos', async () => {
return Todo.query().orderBy('id', 'desc').get();
}).middleware('cors', 'throttle:60,1');
Route.post('/todos', async (request, response) => {
const data = await request.validate({
title: ['required', 'string', 'max:255'],
});
const todo = await Todo.create({ title: data.title, completed: 0 });
return response.json(todo, 201);
}).middleware('cors', 'throttle:30,1');
Route.patch('/todos/{id}', async (request, response) => {
const todo = await Todo.find(request.params.id);
if (!todo) return response.json({ message: 'Todo tidak ditemukan.' }, 404);
const body = await request.all();
todo.fill({
title: body.title ?? todo.title,
completed: body.completed === undefined
? todo.completed
: ([true, 1, '1', 'true'].includes(body.completed) ? 1 : 0),
});
await todo.save();
return response.json(todo);
}).middleware('cors', 'throttle:30,1');
Route.delete('/todos/{id}', async (request, response) => {
const deleted = await Todo.query().where('id', request.params.id).delete();
if (!deleted.changes) return response.json({ message: 'Todo tidak ditemukan.' }, 404);
return response.send('', 204);
}).middleware('cors', 'throttle:30,1');
}
npm run dev
curl -X POST http://127.0.0.1:3333/api/todos \
-H 'Content-Type: application/json' \
-d '{"title":"Pelajari Lanjit"}'
curl http://127.0.0.1:3333/api/todos