Back
Close

Building a Basic Todo List REST API in Node.js with Express

ACT
7,486 views

Persistence

Here is an example of using a database. To do so, the todo model has been extracted from app.js and added as a module in the models folder:

 /
  |
  | - app.js
  | - models/todo.js

Within the todo.js module, a require has been done to the sqlite3 module that enable the use of an in-memory database.

Example of use of persistence
const express = require('express');
const port = 9000;
const app = express();
const postparser = require('./middleware/postparser');
const Todo = require('./models/todo');
app.use(postparser);
app.get('/', function(request, response){
Todo.all((err, todos) => response.status(200).json(todos));
});
app.post('/', (request, response) => {
console.log(request.body);
var newTodo = JSON.parse(request.body);
Todo.add(newTodo);
response.status(201).json();
});
app.put('/:id', (request, response) => {
var id = request.params.id;
var updatedTodo = JSON.parse(request.body);
updatedTodo.id = parseInt(id);
Todo.update(updatedTodo, (err, data) => {
if(err)
{
response.status(404, 'The task is not found').send();
} else {
response.status(204).send(data);
}
});
});
app.delete('/:id', (request, response) => {
var id = parseInt(request.params.id);
Todo.delete(id, (err) => {
if(err){
response.status(404).send();
}else{
response.status(200).send();
}
});
});
app.listen(port);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Now we have to work on the presentation layer.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants