Skip to content

Instantly share code, notes, and snippets.

@blangue
Created June 18, 2022 18:19
Show Gist options
  • Save blangue/3568f49caf83b3955b3625617001a100 to your computer and use it in GitHub Desktop.
Save blangue/3568f49caf83b3955b3625617001a100 to your computer and use it in GitHub Desktop.
First mini-project of micro-service
// index.js
// where your node app starts
// init project
var express = require('express');
var app = express();
// enable CORS (https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)
// so that your API is remotely testable by FCC
var cors = require('cors');
app.use(cors({optionsSuccessStatus: 200})); // some legacy browsers choke on 204
// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));
// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function (req, res) {
res.sendFile(__dirname + '/views/index.html');
});
// your first API endpoint...
// GET /api/:timestamp OR GET /api/:date
app.get("/api/:time", function (req, res, next) {
var date = new Date(req.params.time);
//First invalid error, try as a timestamp
if(date.toString() === "Invalid Date") {
date = new Date(Number(req.params.time));
}
//Second invalid error, throw error
if(date.toString() === "Invalid Date") {
res.json({error: date.toString()});
}
console.log("Bien reçu la date: "+ date.toUTCString());
res.json({unix: date.getTime(), utc: date.toUTCString()});
});
// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
app.get(
"/api/",
(req, res, next) => {
req.time = new Date().toString();
next();
},
(req, res) => {
var date = new Date(req.time);
res.json({unix: date.getTime(), utc: date.toUTCString()});
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment