67 lines
1.7 KiB
JavaScript
67 lines
1.7 KiB
JavaScript
'use strict';
|
|
|
|
const path = require('path');
|
|
const express = require('express');
|
|
const { gregorianToRepublican } = require('./src/republicanCalendar');
|
|
|
|
const app = express();
|
|
const port = process.env.PORT || 3000;
|
|
|
|
app.use(express.static(path.join(__dirname, 'public')));
|
|
app.use('/locales', express.static(path.join(__dirname, 'locales')));
|
|
|
|
function nowUtc() {
|
|
const now = new Date();
|
|
return {
|
|
year: now.getUTCFullYear(),
|
|
month: now.getUTCMonth() + 1,
|
|
day: now.getUTCDate(),
|
|
};
|
|
}
|
|
|
|
function convertAndRespond(res, gregorianDate) {
|
|
try {
|
|
const republicanDate = gregorianToRepublican(gregorianDate);
|
|
res.json({ ok: true, republicanDate });
|
|
} catch (error) {
|
|
if (error.message === 'BEFORE_EPOCH') {
|
|
res.status(400).json({
|
|
ok: false,
|
|
error: 'BEFORE_EPOCH',
|
|
message: 'The Republican calendar begins on 22 September 1792.',
|
|
});
|
|
return;
|
|
}
|
|
res.status(400).json({
|
|
ok: false,
|
|
error: 'INVALID_DATE',
|
|
message: 'The given date does not exist in the Gregorian calendar.',
|
|
});
|
|
}
|
|
}
|
|
|
|
app.get('/api/today', (req, res) => {
|
|
convertAndRespond(res, nowUtc());
|
|
});
|
|
|
|
app.get('/api/convert', (req, res) => {
|
|
const year = Number.parseInt(req.query.year, 10);
|
|
const month = Number.parseInt(req.query.month, 10);
|
|
const day = Number.parseInt(req.query.day, 10);
|
|
|
|
if (!Number.isInteger(year) || !Number.isInteger(month) || !Number.isInteger(day)) {
|
|
res.status(400).json({
|
|
ok: false,
|
|
error: 'INVALID_DATE',
|
|
message: 'year, month and day query parameters are required integers.',
|
|
});
|
|
return;
|
|
}
|
|
|
|
convertAndRespond(res, { year, month, day });
|
|
});
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Calendrier republicain server listening on port ${port}`);
|
|
});
|