-
Notifications
You must be signed in to change notification settings - Fork 333
/
matrix.ts
62 lines (49 loc) · 2.08 KB
/
matrix.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 { Dictionary, HttpParamStyles } from '@stoplight/types';
import { IHttpNameValue, JSONSchema } from '../../../types';
import { IHttpHeaderParamStyleDeserializer } from '../types';
import { createObjectFromKeyValList } from './utils';
export class MatrixStyleDeserializer implements IHttpHeaderParamStyleDeserializer {
public supports(style: HttpParamStyles) {
return style === HttpParamStyles.Matrix;
}
public deserialize(name: string, parameters: IHttpNameValue, schema?: JSONSchema, explode = false): any {
const type = schema ? schema.type : 'undefined';
if (!parameters[name].startsWith(';')) {
throw new Error('Matrix serialization style requires parameter to be prefixed with ";"');
}
const value = parameters[name].substr(1);
if (type === 'array') {
return explode ? this.deserializeImplodeArray(name, value) : this.deserializeArray(name, value);
} else if (type === 'object') {
return explode ? this.deserializeImplodeObject(value) : this.deserializeObject(name, value);
} else {
return this.deserializePrimitive(name, value);
}
}
private deserializePrimitive(name: string, value: string) {
const prefix = name + '=';
if (!value.startsWith(prefix)) {
throw new Error('Matrix serialization style requires parameter to be prefixed with name');
}
return value.substr(prefix.length);
}
private deserializeArray(name: string, value: string) {
const raw = this.deserializePrimitive(name, value);
return raw === '' ? [] : raw.split(',');
}
private deserializeImplodeArray(name: string, value: string) {
if (value === '') {
return [];
}
return value.split(';').map(part => this.deserializePrimitive(name, part));
}
private deserializeImplodeObject(value: string) {
return value.split(';').reduce((result: Dictionary<string>, pair) => {
const [k, v] = pair.split('=');
return { ...result, [k]: v };
}, {});
}
private deserializeObject(name: string, value: string) {
return createObjectFromKeyValList(this.deserializePrimitive(name, value).split(','));
}
}