UNPKG

2.98 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.ContextRunnerImpl = exports.ResultWithContext = void 0;
4const _ = require("lodash");
5const base_1 = require("../base");
6const context_1 = require("../context");
7const select_fields_1 = require("../select-fields");
8const validation_result_1 = require("../validation-result");
9class ResultWithContext extends validation_result_1.Result {
10 constructor(context) {
11 super(error => error, context.errors);
12 this.context = context;
13 }
14}
15exports.ResultWithContext = ResultWithContext;
16class 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 // An instance is mutable, so if an item changed its value, there's no need to call getData again
42 const newValue = instance.value;
43 // Checks whether the value changed.
44 // Avoids e.g. undefined values being set on the request if it didn't have the key initially.
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}
67exports.ContextRunnerImpl = ContextRunnerImpl;