1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.oneOf = void 0;
|
4 | const _ = require("lodash");
|
5 | const chain_1 = require("../chain");
|
6 | const context_builder_1 = require("../context-builder");
|
7 |
|
8 | const dummyItem = { async run() { } };
|
9 | function 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 |
|
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 |
|
20 |
|
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 |
|
33 | surrogateContext.addError(typeof message === 'function' ? message({ req }) : message || 'Invalid value(s)', _.flatMap(allErrors));
|
34 | }
|
35 |
|
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 | }
|
52 | exports.oneOf = oneOf;
|