Skip to content

Instantly share code, notes, and snippets.

@AntonioVdlC

AntonioVdlC/framework.js Secret

Created May 27, 2020
Embed
What would you like to do?
const errors = require("./errors");
const _fromRequest = f => async req => {
const ctx = {};
f.resolvers.forEach((resolver, i) => {
if (!resolver) {
throw new Error(`Incorrect resolver ${resolver} (index #${i} in resolvers array)`);
}
ctx[resolver.name] = resolver(req);
});
return f(ctx);
};
const _runHandler = (resolvers, func) => ctx => {
const validatedCtx = ctx;
return Promise.all(
resolvers.map(async resolver => {
try {
validatedCtx[resolver.name] = resolver.validate(ctx[resolver.name]);
} catch (err) {
throw new errors.ValidationError(resolver.name, err);
}
}),
).then(() => func(validatedCtx));
};
const resolver = (name, resolve, validate) => {
const f = req => {
try {
return resolve(req);
} catch (err) {
throw new errors.RequestContextError(resolver.name, err);
}
};
Object.defineProperty(f, "name", { value: name });
f.validate = validate || (identity => identity);
return f;
};
const handler = (resolvers, func) => {
let f = _runHandler(resolvers, func);
Object.defineProperty(f, "name", { value: func.name });
f.resolvers = resolvers;
f.fromRequest = _fromRequest(f);
return f;
};
module.exports = { handler, resolver };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment