Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 21x 21x 87x 113x 87x 21x 48x 1296x 726x 12x 12x 12x 12x 6x 6x 6x 6x 6x 4x 2x 2x 24x 2x 2x 2x 2x 2x 21x 21x 87x 87x 1x 87x 21x 87x 87x 86x 87x 21x 21x 21x 1x 1x 1x 1x 1x 1x 1x 21x 21x 21x 21x 87x 87x 87x 87x 87x 87x 113x 2x 85x 6x 81x 1296x 570x 726x 726x 72x 72x 288x 288x 222x 222x 72x 72x 72x 72x 726x 726x 726x 726x 15x 15x 21x 21x 21x 21x 21x 15x 5x | const versionValidationMiddleware = require('./middleware/version-validation.middleware.js');
const authenticationMiddleware = require('./middleware/authentication.middleware.js');
const sofScopeMiddleware = require('./middleware/sof-scope.middleware.js');
const { route: metadataConfig } = require('./metadata/metadata.config');
const { routeArgs, routes } = require('./route.config');
const hyphenToCamelcase = require('./utils/hyphen-to-camel.utils');
const { sanitizeMiddleware } = require('./utils/sanitize.utils');
const { getController } = require('./utils/controllers.utils');
const { getSearchParameters } = require('./utils/params.utils');
const { VERSIONS, INTERACTIONS } = require('../constants');
const deprecate = require('./utils/deprecation.notice.js');
const operationsController = require('./operations/operations.controller');
const { container } = require('./winston.js');
const cors = require('cors');
const uniques = (list) => list.filter((val, index, self) => val && self.indexOf(val) === index);
let deprecatedLogger = deprecate(
container.get('default'),
'Using the logger this way is deprecated. Please see the documentation on ' +
'BREAKING CHANGES in version 2.0.0 for instructions on how to upgrade.'
);
/**
* @function getAllConfiguredVersions
* @description Get a unique list of versions provided in profile configurations
* @param {Object} profiles - Profile configurations from end users
* @return {Array<String>} Array of versions we need to support
*/
function getAllConfiguredVersions(profiles = {}) {
let supportedVersions = Object.values(VERSIONS);
let providedVersions = Object.getOwnPropertyNames(profiles).reduce((set, profile_key) => {
let { versions = [] } = profiles[profile_key];
versions.forEach((version) => set.add(version));
return set;
}, new Set());
// Filter the provided versions by ones we actually support. We need to check this to make
// sure some user does not pass in a version we do not officially support in core for whatever
// reason. Otherwise there may be some compliance issues.
return Array.from(providedVersions).filter(
(version) => supportedVersions.indexOf(version) !== -1
);
}
/**
* @function hasValidService
* @description Does this profile have a service with a function whose name
* macthes what the route expects to call when invoked
* @param {object} route - route configuration for this specific route
* @param {object} profile - profile configuration for this particular profile
* @return {boolean}
*/
function hasValidService(route = {}, profile = {}) {
return Boolean(profile.serviceModule && profile.serviceModule[route.interaction]);
}
/**
* @function loadController
* @param {String} lowercaseKey - Profile key
* @param {String} interaction - Interaction needed to perform
* @param {Object} service - Consumer provided service module
* @return {Function} express middleware
*/
function loadController(lowercaseKey, interaction, service) {
return (req, res, next) => {
const { base_version } = req.params;
const fhirVersion = VERSIONS[base_version] || VERSIONS['4_0_1']; // fallback to r4 for custom baseUrl
const controller = getController(fhirVersion, lowercaseKey);
// Invoke the correct interaction on our controller
controller[interaction](service)(req, res, next);
};
}
/**
* @function enableOperationRoutesForProfile
* @description Enable custom operation routes provided by the user
* @param {Object} app - Express application instance
* @param {Object} config - Application config
* @param {Object} profile - Profile configuration from end users
* @param {String} key - Profile name the user has configured
* @param {Array<Object>} parameters - Parameters allowed for this profile
* @param {Object} corsDefaults - Default cors settings
*/
function enableOperationRoutesForProfile(app, config, profile, key, parameters, corsDefaults) {
// Error message we will use for invalid configurations
let errorMessage =
`Invalid operation configuration for ${key}. Please ` +
'see the Operations wiki for instructions on how to use operations. ' +
'https://github.com/Asymmetrik/node-fhir-server-core/wiki/Operations';
for (let op of profile.operation) {
let functionName = hyphenToCamelcase(op.name || '');
let hasController = profile.serviceModule
? Object.keys(profile.serviceModule).includes(functionName)
: false;
// Check for required configurations, must have name, route, method, and
// a matching controller
if (!op.name || !op.route || !op.method || !hasController) {
throw new Error(errorMessage);
}
let lowercaseMethod = op.method.toLowerCase();
let interaction =
lowercaseMethod === 'post' ? INTERACTIONS.OPERATIONS_POST : INTERACTIONS.OPERATIONS_GET;
let route = routes.find((rt) => rt.interaction === interaction);
let corsOptions = Object.assign({}, corsDefaults, {
methods: [route.type.toUpperCase()],
});
Iif (profile.baseUrls && profile.baseUrls.length && profile.baseUrls.includes('/')) {
const operationsRoute = '/'.concat(op.route).replace('$', '([$])');
// Enable cors with preflight
app.options(operationsRoute, cors(corsOptions));
// Enable this operation route
app[route.type](
// We need to allow the $ to exist in these routes
operationsRoute,
cors(corsOptions),
versionValidationMiddleware(profile),
sanitizeMiddleware([routeArgs.BASE, routeArgs.ID, ...parameters]),
authenticationMiddleware(config),
sofScopeMiddleware({ route, auth: config.auth, name: key }),
// TODO: REMOVE: logger in future versions
operationsController[interaction]({ profile, name: functionName, logger: deprecatedLogger })
);
}
const operationRoute = route.path
.replace(':resource', key)
.concat(op.route)
.replace('$', '([$])');
// Enable cors with preflight
app.options(operationRoute, cors(corsOptions));
// Enable this operation route
app[route.type](
// We need to allow the $ to exist in these routes
operationRoute,
cors(corsOptions),
versionValidationMiddleware(profile),
sanitizeMiddleware([routeArgs.BASE, routeArgs.ID, ...parameters]),
authenticationMiddleware(config),
sofScopeMiddleware({ route, auth: config.auth, name: key }),
// TODO: REMOVE: logger in future versions
operationsController[interaction]({ profile, name: functionName, logger: deprecatedLogger })
);
}
}
function enableMetadataRoute(app, config, corsDefaults) {
const { profiles, security, statementGenerator } = config;
const customBaseUrlProfiles = Object.keys(profiles)
.map((profileName) => {
const profile = profiles[profileName];
if (profile.baseUrls && profile.baseUrls.length) {
return profile;
}
})
.filter((profile) => profile);
const inferredProfiles = Object.keys(profiles)
.map((profileName) => {
const profile = profiles[profileName];
if (!profile.baseUrls || !profile.baseUrls.length) {
return profile;
}
})
.filter((profile) => profile);
// Determine which versions need a metadata endpoint, we need to loop through
// all the configured profiles and find all the uniquely provided versions
const versionValidationConfiguration = {
versions: getAllConfiguredVersions(profiles),
};
const corsOptions = Object.assign({}, corsDefaults, {
methods: ['GET'],
});
if (customBaseUrlProfiles.length) {
const baseUrls = uniques(
customBaseUrlProfiles
.map((profile) => profile.baseUrls)
.reduce((accum, val) => accum.concat(val), [])
);
baseUrls.forEach((baseUrl) => {
const metadataPath = baseUrl === '/' ? '/metadata' : `${baseUrl}/metadata`;
app.options(metadataPath, cors(corsOptions));
// Enable metadata route
app.get(
metadataPath,
cors(corsOptions),
sanitizeMiddleware(metadataConfig.args),
metadataConfig.controller({ profiles, security, statementGenerator })
);
});
}
Eif (inferredProfiles.length) {
// Enable cors with preflight
app.options(metadataConfig.path, cors(corsOptions));
// Enable metadata route
app.get(
metadataConfig.path,
cors(corsOptions),
versionValidationMiddleware(versionValidationConfiguration),
sanitizeMiddleware(metadataConfig.args),
metadataConfig.controller({ profiles, security, statementGenerator })
);
}
}
function enableResourceRoutes(app, config, corsDefaults) {
// Iterate over all of our provided profiles
for (let profileName in config.profiles) {
let lowercaseKey = profileName.toLowerCase();
let profile = config.profiles[profileName];
let versions = profile.versions;
// User's can override arguments by providing their own metadata
// function, may have more use in other areas in the future
let overrideArguments = profile.metadata;
// We need to check if the provided key is one this server supports
// so load anything related to the key here and handle with one simple error
let parameters;
try {
parameters = versions.reduce(
(all, version) => all.concat(getSearchParameters(lowercaseKey, version, overrideArguments)),
[]
);
} catch (err) {
throw new Error(
`${profileName} is an invalid profile configuration, please see the wiki for ` +
'instructions on how to enable a profile in your server, ' +
'https://github.com/Asymmetrik/node-fhir-server-core/wiki/Profile'
);
}
// Enable all provided operations for this profile
if (profile.operation && profile.operation.length) {
enableOperationRoutesForProfile(app, config, profile, profileName, parameters, corsDefaults);
}
// Start iterating over potential routes to enable for this profile
for (let route of routes) {
// If we do not have a matching service function for this route, skip it
if (!hasValidService(route, profile)) {
continue;
}
// Calculate the cors setting we want for this route
let corsOptions = Object.assign({}, corsDefaults, profile.corsOptions, {
methods: [route.type.toUpperCase()],
});
// Define the arguments based on the interactions
switch (route.interaction) {
case INTERACTIONS.CREATE:
route.args = [routeArgs.BASE];
break;
case INTERACTIONS.SEARCH_BY_ID:
case INTERACTIONS.UPDATE:
case INTERACTIONS.DELETE:
case INTERACTIONS.PATCH:
route.args = [routeArgs.BASE, routeArgs.ID];
break;
case INTERACTIONS.SEARCH:
case INTERACTIONS.HISTORY:
route.args = [routeArgs.BASE, ...parameters];
break;
case INTERACTIONS.HISTORY_BY_ID:
case INTERACTIONS.EXPAND_BY_ID:
route.args = [routeArgs.BASE, routeArgs.ID, ...parameters];
break;
case INTERACTIONS.SEARCH_BY_VID:
route.args = [routeArgs.BASE, routeArgs.ID, routeArgs.VERSION_ID];
break;
}
Iif (profile.baseUrls && profile.baseUrls.includes('/')) {
let profileRoute = route.path
.replace(':resource', profileName)
.replace(':base_version/', '');
// Enable cors with preflight
app.options(profileRoute, cors(corsOptions));
// Enable this operation route
app[route.type](
profileRoute,
cors(corsOptions),
sanitizeMiddleware(route.args),
authenticationMiddleware(config),
sofScopeMiddleware({ route, auth: config.auth, name: profileName }),
loadController(lowercaseKey, route.interaction, profile.serviceModule)
);
} else {
let profileRoute = route.path.replace(':resource', profileName);
// Enable cors with preflight
app.options(profileRoute, cors(corsOptions));
// Enable this operation route
app[route.type](
profileRoute,
cors(corsOptions),
versionValidationMiddleware(profile),
sanitizeMiddleware(route.args),
authenticationMiddleware(config),
sofScopeMiddleware({ route, auth: config.auth, name: profileName }),
loadController(lowercaseKey, route.interaction, profile.serviceModule)
);
}
}
}
}
function enableBaseRoute(app, config, corsDefaults) {
// Determine which versions need a base endpoint, we need to loop through
// all the configured profiles and find all the uniquely provided versions
let routes = require('./base/base.config');
for (let i; routes.length; i++) {
let versionValidationConfiguration = {
versions: getAllConfiguredVersions(config.profiles),
};
let corsOptions = Object.assign({}, corsDefaults, {
methods: [routes[i].type.toUpperCase()],
});
// Enable cors with preflight
app.options(routes[i].path, cors(corsOptions));
// Enable base route
app[routes[i].type](
routes[i].path,
cors(corsOptions),
versionValidationMiddleware(versionValidationConfiguration),
sanitizeMiddleware(routes[i].args),
routes[i].controller({ config })
);
}
}
function setRoutes(options = {}) {
let { app, config } = options;
let { server } = config;
// Setup default cors options
let corsDefaults = Object.assign({}, server.corsOptions);
// Enable all routes, operations are enabled inside enableResourceRoutes
enableMetadataRoute(app, config, corsDefaults);
enableResourceRoutes(app, config, corsDefaults);
// Enable all routes, operations base: Batch and Transactions
enableBaseRoute(app, config, corsDefaults);
}
module.exports = {
setRoutes,
};
|