Files
mina-sidor-fa-web/mock-api/dafa-web/server.js
Erik Tiekstra d003842e4e feat(api): Reflected api-changes to different api-requests and fixed mock-api. (TV-371)
Squashed commit of the following:

commit 01ef668c8ddd8e0d8ff459d60f45ca0c7780f184
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Tue Aug 17 11:53:36 2021 +0200

    Fixed issue with authentication

commit e40f4728203388175f405184693b3604001afc5e
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Tue Aug 17 11:09:46 2021 +0200

    Added some more fixes to API requests based on latest changes

commit 920eb03302ee65852141f7bcce72d832507d2c07
Merge: c2d5d7c bfa8ed5
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Tue Aug 17 09:34:48 2021 +0200

    Merge branch 'develop' into feature/TV-371-api-fix

commit c2d5d7c9a7b812a57234b0038da79bc1d0c07881
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Tue Aug 17 07:50:11 2021 +0200

    Updated mock-api

commit 5578b0ffdba27e0e80dabe05e920b96e46331fb0
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Mon Aug 16 15:17:46 2021 +0200

    Fixed fetching of userinfo and organizations

commit 116b3092bf9a685354738146ef7cd0eb619fa009
Merge: 6a32f19 01dc4b3
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Mon Aug 16 13:09:53 2021 +0200

    Merge branch 'develop' into feature/TV-371-api-fix

commit 6a32f1997e9ddb912cf2995a333faa9aa0205852
Author: Erik Tiekstra <erik.tiekstra@arbetsformedlingen.se>
Date:   Mon Aug 16 13:07:38 2021 +0200

    Updated API-endpoints
2021-08-17 11:55:22 +02:00

141 lines
4.2 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*onlyEmployeesWithoutAuthorization=*': '/employee$1authorizations.length_gte=1',
'/employee*': '/employees$1',
'/participants': '/participants?_embed=employees',
'/participant/:id': '/participants/:id?_embed=employees',
'/auth/userinfo': '/currentUser',
'/auth/organizations': '/currentUser',
'/avrop/tjanster*': '/tjanster$1',
'/avrop/utforandeverksamheter*': '/organizations$1',
'/avrop/kommuner*': '/kommuner$1',
'/deltagare': '/avrop',
'/deltagare/:sokandeId/avrop': '/avrop?sokandeId=:sokandeId',
'/deltagare/:sokandeId/*': '/deltagare/:sokandeId',
'*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 method = req.originalMethod;
const parsedUrl = method === 'GET' ? req._parsedOriginalUrl : req._parsedUrl;
const pathname = parsedUrl.pathname;
const params = parsedUrl.query ? new URLSearchParams(parsedUrl.query) : null;
const requestHeaders = req.headers;
// all paths except /auth/token requires Authorization header.
if (!pathname.includes('/auth/token') && !requestHeaders.authorization) {
return res.status(401).jsonp({ error: 'No valid access-token' });
}
// Return custom error when status is 404.
if (res.statusCode === 404) {
return res.status(404).jsonp({ error: `Can't find path: ${pathname}` });
}
// Add createdAt to the body
if (method === 'POST') {
req.body.createdAt = Date.now();
}
let data = res.locals.data;
const deltagareRegex = /(?:\/deltagare\/)(?:\d\/)(contact|driverlicense|educationlevels\/highest|educations|translator|work\/disabilities|work\/languages|work\/experiences)/g;
const isDeltagarePath = deltagareRegex.exec(pathname);
const avropRegex = /(?:\/avrop\/(?:tjanster|utforandeverksamheter|kommuner|\d))|(?:\/deltagare\/\d\/(avrop))/g;
const isAvropPath = avropRegex.exec(pathname);
const authRegex = /(?:\/auth\/)(userinfo|organizations)/g;
const isAuthPath = authRegex.exec(pathname);
if (isAuthPath) {
const authSubPath = isAuthPath[1];
if (authSubPath === 'organizations') {
data = res.locals.data[authSubPath].map(organization => ({
name: organization.name,
organizationnumber: organization.organizationNumber,
}));
}
}
if (isDeltagarePath) {
const deltagareSubPath = getDeltagareSubPath(isDeltagarePath[1]);
data = res.locals.data[deltagareSubPath] || {};
}
if (isAvropPath) {
if (params) {
const newData = [];
params.forEach((value, key) => {
if (key === 'kommunCodes') {
value = +value;
}
newData.push(...data.filter(item => item[`related_${key}`].includes(value)));
});
data = newData.filter((value, index, arr) => arr.findIndex(item => item.code === value.code) === index);
} else if (isAvropPath[1]) {
data = data[0];
}
}
res.jsonp({
data,
...appendMetaData(params, res),
});
};
server.use(router);
server.listen(8000, () => {
console.info('JSON Server is running');
});
function appendMetaData(params, res) {
if (params && 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 'educationlevels/highest':
return 'highestEducation';
case 'work/disabilities':
return 'disabilities';
case 'work/languages':
return 'workLanguages';
case 'work/experiences':
return 'workExperiences';
default:
return path;
}
}