1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.ContextRunnerImpl = exports.ResultWithContext = void 0;
|
4 | const _ = require("lodash");
|
5 | const base_1 = require("../base");
|
6 | const context_1 = require("../context");
|
7 | const select_fields_1 = require("../select-fields");
|
8 | const validation_result_1 = require("../validation-result");
|
9 | class ResultWithContext extends validation_result_1.Result {
|
10 | constructor(context) {
|
11 | super(error => error, context.errors);
|
12 | this.context = context;
|
13 | }
|
14 | }
|
15 | exports.ResultWithContext = ResultWithContext;
|
16 | class ContextRunnerImpl {
|
17 | constructor(builderOrContext, selectFields = select_fields_1.selectFields) {
|
18 | this.builderOrContext = builderOrContext;
|
19 | this.selectFields = selectFields;
|
20 | }
|
21 | async run(req, options = {}) {
|
22 | const context = this.builderOrContext instanceof context_1.Context
|
23 | ? this.builderOrContext
|
24 | : this.builderOrContext.build();
|
25 | const instances = this.selectFields(req, context.fields, context.locations);
|
26 | context.addFieldInstances(instances);
|
27 | const haltedInstances = new Set();
|
28 | for (const contextItem of context.stack) {
|
29 | const promises = context.getData({ requiredOnly: true }).map(async (instance) => {
|
30 | const { location, path } = instance;
|
31 | const instanceKey = `${location}:${path}`;
|
32 | if (haltedInstances.has(instanceKey)) {
|
33 | return;
|
34 | }
|
35 | try {
|
36 | await contextItem.run(context, instance.value, {
|
37 | req,
|
38 | location,
|
39 | path,
|
40 | });
|
41 |
|
42 | const newValue = instance.value;
|
43 |
|
44 |
|
45 | const reqValue = path !== '' ? _.get(req[location], path) : req[location];
|
46 | if (!options.dryRun && reqValue !== instance.value) {
|
47 | path !== '' ? _.set(req[location], path, newValue) : _.set(req, location, newValue);
|
48 | }
|
49 | }
|
50 | catch (e) {
|
51 | if (e instanceof base_1.ValidationHalt) {
|
52 | haltedInstances.add(instanceKey);
|
53 | return;
|
54 | }
|
55 | throw e;
|
56 | }
|
57 | });
|
58 | await Promise.all(promises);
|
59 | }
|
60 | if (!options.dryRun) {
|
61 | const internalReq = req;
|
62 | internalReq[base_1.contextsKey] = (internalReq[base_1.contextsKey] || []).concat(context);
|
63 | }
|
64 | return new ResultWithContext(context);
|
65 | }
|
66 | }
|
67 | exports.ContextRunnerImpl = ContextRunnerImpl;
|