Created
December 5, 2018 18:58
-
-
Save devdbrandy/93afdf42203830c72cee840102e2b2a2 to your computer and use it in GitHub Desktop.
Simple Express API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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