Skip to content

Instantly share code, notes, and snippets.

@oismaelash
Created April 4, 2024 19:27
Show Gist options
  • Save oismaelash/021f5fa955bdf02e0770c48545a401dc to your computer and use it in GitHub Desktop.
Save oismaelash/021f5fa955bdf02e0770c48545a401dc to your computer and use it in GitHub Desktop.
import express from 'express'
const app = express()
const heroService = new HeroService()
let heroes = []
class HeroService(){
function getHeros(){
return heroes;
}
function getHero(id){
return heroes.find(hero => heroes.id == id)
}
function createHero(hero){
heroes.push(hero)
}
function updateHero(id, hero){
let hero = heroes.find(hero => heroes.id == id)
hero = {...hero, hero}
heroes.push(hero)
}
function deleteHero(id){
delete heroes[id]
return 'deleted'
}
}
app.get('/api/hero', (req, res) => {
return res.status(200).json(heroService.getHeroes())
})
app.get('/api/hero/:id', (req, res) =>{
const id = req.params.id
const hero = heroService.getHero(id)
if (hero) {
return res.status(200).json(hero)
}
return res.status(404)
})
app.post('/api/hero', (req, res) => {
const body = req.body
return res.status(201).json(heroService.createHero(body))
})
app.put('/api/hero/:id', (req, res) => {
const id = req.params.id
const body = req.body
const hero = heroService.getHero(id)
if (hero) {
return res.status(200).json(heroService.updateHero(id, body))
}
return res.status(404)
})
app.delete('/api/hero/:id', (req, res) => {
const id = req.params.id
const hero = heroService.getHero(id)
if (hero) {
return res.status(200).json(heroService.deleteHero(id))
}
return res.status(404)
})
app.listen(3000, () =>
console.log(`App listening on port ${3000}!`),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment