Skip to content

Instantly share code, notes, and snippets.

@devdbrandy
Created Dec 5, 2018
Embed
What would you like to do?
Simple Express API
/* eslint-disable */
const express = require('express');
const app = express();
app.use(express.json());
const db = {
users: [
{
id: 1,
name: 'John Doe',
},
{
id: 2,
name: 'Jane Doe'
},
{
id: 3,
name: 'Alex Song',
},
],
};
class User {
constructor(attr) {
User.count += 1;
this.id = User.count;
this.name = attr.name;
}
static create(attr) {
const user = new User(attr);
User.table.push(user);
return user;
}
static findById(id) {
return User.table.find(user => user.id === id);
}
static all() {
return User.table;
}
}
User.table = db.users;
User.count = db.users.length;
app.get('/api/users', (req, res, next) => {
res.status(200)
.json({
status: 'OK',
data: User.all(),
});
});
app.get('/api/users/:id', (req, res, next) => {
const userId = parseInt(req.params.id, 10);
const user = User.findById(userId);
res.status(200)
.json({
status: 'OK',
data: [user],
});
});
app.post('/api/users', (req, res, next) => {
const data = req.body;
const newUser = User.create(data);
res.status(201)
.json({
status: 201,
data: [newUser],
});
});
app.post('/api/users', (req, res, next) => {
const data = req.body;
const newUser = User.create(data);
res.status(201)
.json({
status: 201,
data: [newUser],
});
});
module.exports = app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment