Created
September 13, 2017 08:51
-
-
Save avermeulen/f5fb448710d269a11c53bb1e2643752a to your computer and use it in GitHub Desktop.
Simple API using ExpressJS
This file contains hidden or 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
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
let app = express(); | |
// parse application/x-www-form-urlencoded | |
app.use(bodyParser.urlencoded({ extended: false })) | |
// parse application/json | |
app.use(bodyParser.json()) | |
app.use(express.static("public")); | |
var scores = [{ | |
team1 : "Busy Bees", | |
team2 : "Langa Leopards", | |
score : "32-13", | |
date : "09-09-2017" | |
}, | |
{ | |
team1 : "Zebras", | |
team2 : "Young ideas", | |
score : "32-13", | |
date : "09-09-2017" | |
}, | |
{ | |
team1 : "Zebras", | |
team2 : "Young ideas", | |
score : "32-13", | |
date : "08-08-2017" | |
} | |
]; | |
app.get("/api/scores/latest", function(req, res){ | |
res.json(scores); | |
}); | |
app.get("/api/matches/:date", function(req, res){ | |
var date = req.params.date; | |
if (!date){ | |
return res.json({ | |
status : "error", | |
type : "date_not_supplied" | |
}) | |
} | |
var scoresForDay = scores.filter(function (score) { | |
return score.date === date; | |
}); | |
res.json({ | |
status : "success", | |
type : "scores_for_day", | |
data : scoresForDay | |
}) | |
}) | |
app.post("/api/scores", function(req, res){ | |
console.log(req.body); | |
let score = { | |
team1 : req.body.team1, | |
team2 : req.body.team2, | |
score : req.body.score, | |
date : req.body.date | |
} | |
scores.push(score); | |
res.json({ | |
status : "success", | |
type : "score_added", | |
timestamp : new Date(), | |
data : score | |
}); | |
}); | |
app.listen(3007); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment