-
Notifications
You must be signed in to change notification settings - Fork 333
/
form.ts
62 lines (48 loc) · 1.88 KB
/
form.ts
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
import { HttpParamStyles } from '@stoplight/types';
import { IHttpNameValues, JSONSchema } from '../../../types';
import { IHttpQueryParamStyleDeserializer } from '../types';
import { createObjectFromKeyValList } from './utils';
export class FormStyleDeserializer implements IHttpQueryParamStyleDeserializer {
public supports(style: HttpParamStyles) {
return style === HttpParamStyles.Form;
}
public deserialize(name: string, parameters: IHttpNameValues, schema?: JSONSchema, explode = true) {
const type = schema ? schema.type : undefined;
const values = parameters[name];
if (!values) return undefined;
if (type === 'array') {
return explode ? this.deserializeImplodeArray(values) : this.deserializeArray(values);
} else if (type === 'object') {
return explode ? this.deserializeImplodeObject(parameters, schema || {}) : this.deserializeObject(values);
} else {
return values;
}
}
private deserializeImplodeArray(value: string | string[]) {
return Array.isArray(value) ? value : [value];
}
private deserializeArray(value: string | string[]) {
if (Array.isArray(value)) {
// last query param is taken into account
value = value[value.length - 1];
}
return value.split(',');
}
private deserializeImplodeObject(parameters: IHttpNameValues, schema: JSONSchema) {
const properties = schema.properties || {};
return Object.keys(parameters).reduce((result: object, key) => {
const value = parameters[key];
if (!Object.prototype.hasOwnProperty.call(properties, key)) {
return result;
}
return { ...result, [key]: value };
}, {});
}
private deserializeObject(value: string | string[]) {
if (Array.isArray(value)) {
// last query param is taken into account
value = value[value.length - 1];
}
return createObjectFromKeyValList(value.split(','));
}
}