Skip to content

Instantly share code, notes, and snippets.

@devdbrandy
Created December 5, 2018 18:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devdbrandy/93afdf42203830c72cee840102e2b2a2 to your computer and use it in GitHub Desktop.
Save devdbrandy/93afdf42203830c72cee840102e2b2a2 to your computer and use it in GitHub Desktop.
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