UNPKG

2.39 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.oneOf = void 0;
4const _ = require("lodash");
5const chain_1 = require("../chain");
6const context_builder_1 = require("../context-builder");
7// A dummy context item that gets added to surrogate contexts just to make them run
8const dummyItem = { async run() { } };
9function oneOf(chains, message) {
10 let result;
11 const middleware = async (req, _res, next) => {
12 const surrogateContext = new context_builder_1.ContextBuilder().addItem(dummyItem).build();
13 // Run each group of chains in parallel, and within each group, run each chain in parallel too.
14 const promises = chains.map(async (chain) => {
15 const group = Array.isArray(chain) ? chain : [chain];
16 const results = await Promise.all(group.map(chain => chain.run(req, { dryRun: true })));
17 const contexts = results.map(result => result.context);
18 const groupErrors = _.flatMap(contexts, 'errors');
19 // #536: The data from a chain within oneOf() can only be made available to e.g. matchedData()
20 // if its entire group is valid.
21 if (!groupErrors.length) {
22 contexts.forEach(context => {
23 surrogateContext.addFieldInstances(context.getData());
24 });
25 }
26 return groupErrors;
27 });
28 try {
29 const allErrors = await Promise.all(promises);
30 const success = allErrors.some(groupErrors => groupErrors.length === 0);
31 if (!success) {
32 // Only add an error to the context if no group of chains had success.
33 surrogateContext.addError(typeof message === 'function' ? message({ req }) : message || 'Invalid value(s)', _.flatMap(allErrors));
34 }
35 // Final context running pass to ensure contexts are added and values are modified properly
36 result = await new chain_1.ContextRunnerImpl(surrogateContext).run(req);
37 next();
38 }
39 catch (e) {
40 next(e);
41 }
42 };
43 const run = async (req) => {
44 return new Promise((resolve, reject) => {
45 middleware(req, {}, (e) => {
46 e ? reject(e) : resolve(result);
47 });
48 });
49 };
50 return Object.assign(middleware, { run });
51}
52exports.oneOf = oneOf;