2021-04-16 04:34:29 +00:00
|
|
|
import createLoaders from './loaders.js';
|
|
|
|
|
import createDebug from 'debug';
|
2017-10-19 08:00:21 +00:00
|
|
|
|
2021-04-16 04:34:29 +00:00
|
|
|
const debug = createDebug('graphbrainz:context');
|
2017-10-19 08:00:21 +00:00
|
|
|
|
2017-11-07 05:54:56 +00:00
|
|
|
export function extendContext(extension, context, options) {
|
2017-10-19 08:00:21 +00:00
|
|
|
if (extension.extendContext) {
|
|
|
|
|
if (typeof extension.extendContext === 'function') {
|
2017-11-07 05:54:56 +00:00
|
|
|
debug(
|
2021-04-10 18:37:01 +00:00
|
|
|
`Extending context via a function from the “${extension.name}” extension.`
|
2021-04-16 04:34:29 +00:00
|
|
|
);
|
|
|
|
|
context = extension.extendContext(context, options);
|
2017-10-19 08:00:21 +00:00
|
|
|
} else {
|
|
|
|
|
throw new Error(
|
|
|
|
|
`Extension “${extension.name}” contains an invalid \`extendContext\` ` +
|
2017-11-07 05:54:56 +00:00
|
|
|
`value: ${extension.extendContext}`
|
2021-04-16 04:34:29 +00:00
|
|
|
);
|
2017-10-19 08:00:21 +00:00
|
|
|
}
|
|
|
|
|
}
|
2021-04-16 04:34:29 +00:00
|
|
|
return context;
|
2017-10-19 08:00:21 +00:00
|
|
|
}
|
|
|
|
|
|
2017-11-07 05:54:56 +00:00
|
|
|
export function createContext(options = {}) {
|
2021-04-16 04:34:29 +00:00
|
|
|
const { client, extensions = [] } = options;
|
|
|
|
|
const loaders = createLoaders(client);
|
|
|
|
|
let context = { client, loaders };
|
2017-11-05 19:59:39 +00:00
|
|
|
return extensions.reduce((context, extension) => {
|
2021-04-16 04:34:29 +00:00
|
|
|
return extendContext(extension, context, options);
|
|
|
|
|
}, context);
|
2017-10-19 08:00:21 +00:00
|
|
|
}
|