99 lines
2.7 KiB
JavaScript
99 lines
2.7 KiB
JavaScript
import jsonServer from 'json-server';
|
|
|
|
const server = jsonServer.create();
|
|
const router = jsonServer.router('api.json');
|
|
const middlewares = jsonServer.defaults();
|
|
|
|
server.use(middlewares);
|
|
|
|
server.use(
|
|
jsonServer.rewriter({
|
|
'/api/*': '/$1',
|
|
'*sort=services*': '$1sort=services[0].name$2',
|
|
'*sort=organizations*': '$1sort=organizations[0].address.city$2',
|
|
'/employee*search=*': '/employee$1fullName_like=$2',
|
|
'/employee*': '/employees$1',
|
|
'/participants': '/participants?_embed=employees',
|
|
'/participant/:id': '/participants/:id?_embed=employees',
|
|
'/auth': '/currentUser',
|
|
'/customerinfo/*/*': '/deltagare/$2',
|
|
'/customerinfo': '/deltagare',
|
|
'*page=*': '$1_page=$2',
|
|
'*limit=*': '$1_limit=$2',
|
|
'*sort=*': '$1_sort=$2',
|
|
'*order=*': '$1_order=$2',
|
|
'/auth/token?accessCode=auth_code_from_CIAM_with_all_permissions': '/getTokenFullAccess',
|
|
})
|
|
);
|
|
|
|
router.render = (req, res) => {
|
|
const pathname = req._parsedOriginalUrl.pathname;
|
|
// all paths except /auth/token requires Authorization header.
|
|
if (!pathname.includes('/auth/token') && !req.headers.authorization) {
|
|
return res.status(401).jsonp({ error: 'No valid access-token' });
|
|
}
|
|
|
|
const params = new URLSearchParams(req._parsedUrl.query);
|
|
|
|
// Add createdAt to the body
|
|
if (req.originalMethod === 'POST') {
|
|
req.body.createdAt = Date.now();
|
|
}
|
|
|
|
if (pathname.includes('/auth/token')) {
|
|
res.jsonp(res.locals.data);
|
|
} else {
|
|
let data = res.locals.data;
|
|
const deltagareRegex = /(?:\/customerinfo\/)(contact|driverlicense|education\/highest|education|translator|work\/disability|work\/languages|work\/experience)/g;
|
|
const isDeltagarePath = deltagareRegex.exec(pathname);
|
|
|
|
if (isDeltagarePath) {
|
|
const deltagareSubPath = getDeltagareSubPath(isDeltagarePath[1]);
|
|
data = res.locals.data[deltagareSubPath] || {};
|
|
}
|
|
res.jsonp({
|
|
data,
|
|
...appendMetaData(params, res),
|
|
});
|
|
}
|
|
};
|
|
|
|
server.use(router);
|
|
server.listen(8000, () => {
|
|
console.info('JSON Server is running');
|
|
});
|
|
|
|
function appendMetaData(params, res) {
|
|
if (params.has('_page')) {
|
|
const limit = +params.get('_limit');
|
|
const page = +params.get('_page');
|
|
const count = res.get('X-Total-Count');
|
|
const totalPages = Math.ceil(count / limit);
|
|
return {
|
|
meta: {
|
|
count,
|
|
limit,
|
|
page,
|
|
totalPages,
|
|
},
|
|
};
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
function getDeltagareSubPath(path) {
|
|
switch (path) {
|
|
case 'education/highest':
|
|
return 'highestEducation';
|
|
case 'work/disability':
|
|
return 'disabilities';
|
|
case 'work/languages':
|
|
return 'workLanguages';
|
|
case 'work/experience':
|
|
return 'workExperiences';
|
|
default:
|
|
return path;
|
|
}
|
|
}
|