opt-cc/api/routes/signatures.js

55 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-03-12 09:26:44 +01:00
'use strict';
2017-05-10 11:04:06 +02:00
// modules
const fs = require('fs');
const express = require('express');
// HTTP status codes by name
const codes = require('./http-codes');
const routerHandling = require('../middleware/router-handling');
const UserModel = require('../models/user');
const signatures = new express.Router();
2017-05-10 11:04:06 +02:00
// routes **********************
signatures.route('/:id')
2018-02-26 09:04:27 +01:00
// does not use idValidator since it works by username
.get((req, res, next) => {
// decode UTF8-escape sequences (special characters)
const uri = decodeURIComponent(req.params.id);
UserModel.findOne({username: uri}, (err, user) => {
const emptyFile = 'resource/signature/0.png';
if (user === null) {
res.sendFile(emptyFile, {root: __dirname + '/../'});
} else {
const file = 'resource/signature/' + user._id + '.png';
fs.stat(__dirname + '/../' + file, (err, stat) => {
if (err === null) {
res.sendFile(file, {root: __dirname + '/../'});
} else if (err.code === 'ENOENT') {
res.sendFile(emptyFile, {root: __dirname + '/../'});
} else {
2018-03-12 09:26:44 +01:00
err = new Error('Internal server error');
2018-02-26 09:04:27 +01:00
err.status = codes.servererror;
return next(err);
}
});
}
2018-03-12 09:26:44 +01:00
});
2018-02-26 09:04:27 +01:00
})
.all(
routerHandling.httpMethodNotAllowed
);
2017-05-10 11:04:06 +02:00
// this middleware function can be used, if you like or remove it
// it looks for object(s) in res.locals.items and if they exist, they are send to the client as json
signatures.use(routerHandling.emptyResponse);
module.exports = signatures;