UNPKG

2.31 kBJavaScriptView Raw
1'use strict'
2
3const { red } = require('./detect/colors')
4const { check } = require('./mapping')
5const {
6 $configuration,
7 $configurationRequests,
8 $mappingChecked
9} = require('./symbols')
10
11async function checkMappings (configuration, mappings) {
12 for await (const mapping of mappings) {
13 if (!mapping[$mappingChecked]) {
14 await check(configuration, mapping)
15 }
16 }
17}
18
19module.exports = class IConfiguration {
20 constructor (configuration) {
21 this[$configuration] = configuration
22 }
23
24 get handlers () {
25 return Object.assign({}, this[$configuration].handlers)
26 }
27
28 get mappings () {
29 return [].concat(this[$configuration].mappings)
30 }
31
32 async setMappings (mappings, request, timeout = 5000) {
33 const configuration = this[$configuration]
34 await checkMappings(configuration, mappings)
35 const configurationRequests = configuration[$configurationRequests]
36 const contexts = [...configurationRequests.contexts]
37 const requestContext = contexts.filter(({ request: candidate }) => candidate === request)[0]
38 const requestsHolding = contexts.filter(candidate => candidate !== requestContext).map(({ holding }) => holding)
39 const holding = Promise.race([
40 Promise.all(requestsHolding),
41 new Promise((resolve, reject) => setTimeout(() => {
42 reject(new Error('iconfiguration.setMappings appears to be blocked'))
43 }, timeout))
44 ])
45 .then(() => {
46 configuration.mappings = mappings
47 })
48 configurationRequests.holding = holding.then(undefined, () => {}) // Absorb error to unblock server
49 holding.then(undefined, () => {
50 console.log(red('REserve blocked during configuration.setMappings'))
51 console.table(contexts.map(context => {
52 const { emitParameters, request, released } = context
53 let info
54 if (emitParameters.statusCode) {
55 info = { statusCode: emitParameters.statusCode }
56 } else if (released) {
57 info = 'exclude-from-holding-list'
58 } else if (context === requestContext) {
59 info = 'configure.setMappings'
60 } else {
61 info = { ms: (new Date() - emitParameters.start) } // + ' ms'
62 }
63 return {
64 method: request.method,
65 url: request.url,
66 info
67 }
68 }))
69 })
70 return holding
71 }
72}