forked from badges/shields
/
endpoint-common.js
83 lines (75 loc) · 2.11 KB
/
endpoint-common.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use strict'
const Joi = require('@hapi/joi')
const validate = require('../core/base-service/validate')
const { InvalidResponse } = require('.')
const optionalStringWhenNamedLogoPresent = Joi.alternatives().when(
'namedLogo',
{
is: Joi.string().required(),
then: Joi.string(),
}
)
const optionalNumberWhenAnyLogoPresent = Joi.alternatives()
.when('namedLogo', { is: Joi.string().required(), then: Joi.number() })
.when('logoSvg', { is: Joi.string().required(), then: Joi.number() })
const endpointSchema = Joi.object({
schemaVersion: 1,
label: Joi.string()
.allow('')
.required(),
message: Joi.string().required(),
color: Joi.string(),
labelColor: Joi.string(),
isError: Joi.boolean().default(false),
namedLogo: Joi.string(),
logoSvg: Joi.string(),
logoColor: optionalStringWhenNamedLogoPresent,
logoWidth: optionalNumberWhenAnyLogoPresent,
logoPosition: optionalNumberWhenAnyLogoPresent,
style: Joi.string(),
cacheSeconds: Joi.number()
.integer()
.min(0),
})
// `namedLogo` or `logoSvg`; not both.
.oxor('namedLogo', 'logoSvg')
.required()
// Strictly validate according to the endpoint schema. This rejects unknown /
// invalid keys. Optionally it prints those keys in the message in order to
// provide detailed feedback.
function validateEndpointData(
data,
{ prettyErrorMessage = 'invalid response data', includeKeys = false } = {}
) {
return validate(
{
ErrorClass: InvalidResponse,
prettyErrorMessage,
includeKeys,
traceErrorMessage: 'Response did not match schema',
traceSuccessMessage: 'Response after validation',
allowAndStripUnknownKeys: false,
},
data,
endpointSchema
)
}
const anySchema = Joi.any()
async function fetchEndpointData(
serviceInstance,
{ url, errorMessages, validationPrettyErrorMessage, includeKeys }
) {
const json = await serviceInstance._requestJson({
schema: anySchema,
url,
errorMessages,
})
return validateEndpointData(json, {
prettyErrorMessage: validationPrettyErrorMessage,
includeKeys,
})
}
module.exports = {
validateEndpointData,
fetchEndpointData,
}