-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathobjectSerializer.ts
More file actions
506 lines (468 loc) · 22.1 KB
/
objectSerializer.ts
File metadata and controls
506 lines (468 loc) · 22.1 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
export * from "./models";
import { AccountHolder } from "./accountHolder";
import { AccountHolderCapability } from "./accountHolderCapability";
import { AccountHolderNotificationData } from "./accountHolderNotificationData";
import { AccountHolderNotificationRequest } from "./accountHolderNotificationRequest";
import { AccountSupportingEntityCapability } from "./accountSupportingEntityCapability";
import { Address } from "./address";
import { Amount } from "./amount";
import { Authentication } from "./authentication";
import { Balance } from "./balance";
import { BalanceAccount } from "./balanceAccount";
import { BalanceAccountNotificationData } from "./balanceAccountNotificationData";
import { BalanceAccountNotificationRequest } from "./balanceAccountNotificationRequest";
import { BalancePlatformNotificationResponse } from "./balancePlatformNotificationResponse";
import { BankAccountDetails } from "./bankAccountDetails";
import { BankScoreSignalTriggeredData } from "./bankScoreSignalTriggeredData";
import { BulkAddress } from "./bulkAddress";
import { CapabilityProblem } from "./capabilityProblem";
import { CapabilityProblemEntity } from "./capabilityProblemEntity";
import { CapabilityProblemEntityRecursive } from "./capabilityProblemEntityRecursive";
import { CapabilitySettings } from "./capabilitySettings";
import { Card } from "./card";
import { CardConfiguration } from "./cardConfiguration";
import { CardOrderItem } from "./cardOrderItem";
import { CardOrderItemDeliveryStatus } from "./cardOrderItemDeliveryStatus";
import { CardOrderNotificationRequest } from "./cardOrderNotificationRequest";
import { ContactDetails } from "./contactDetails";
import { DeliveryAddress } from "./deliveryAddress";
import { DeliveryContact } from "./deliveryContact";
import { Device } from "./device";
import { Expiry } from "./expiry";
import { IbanAccountIdentification } from "./ibanAccountIdentification";
import { Name } from "./name";
import { NetworkTokenNotificationDataV2 } from "./networkTokenNotificationDataV2";
import { NetworkTokenNotificationRequest } from "./networkTokenNotificationRequest";
import { NetworkTokenRequestor } from "./networkTokenRequestor";
import { NetworkTokenRiskRuleData } from "./networkTokenRiskRuleData";
import { NetworkTokenRiskRuleSource } from "./networkTokenRiskRuleSource";
import { NetworkTokenTransactionRulesResult } from "./networkTokenTransactionRulesResult";
import { NetworkTokenTriggeredRiskRule } from "./networkTokenTriggeredRiskRule";
import { PaymentInstrument } from "./paymentInstrument";
import { PaymentInstrumentAdditionalBankAccountIdentificationsInnerClass } from "./paymentInstrumentAdditionalBankAccountIdentificationsInner";
import { PaymentInstrumentNotificationData } from "./paymentInstrumentNotificationData";
import { PaymentNotificationRequest } from "./paymentNotificationRequest";
import { Phone } from "./phone";
import { PhoneNumber } from "./phoneNumber";
import { PlatformPaymentConfiguration } from "./platformPaymentConfiguration";
import { RemediatingAction } from "./remediatingAction";
import { Resource } from "./resource";
import { ResourceReference } from "./resourceReference";
import { ScoreNotificationRequest } from "./scoreNotificationRequest";
import { SweepConfigurationNotificationData } from "./sweepConfigurationNotificationData";
import { SweepConfigurationNotificationRequest } from "./sweepConfigurationNotificationRequest";
import { SweepConfigurationV2 } from "./sweepConfigurationV2";
import { SweepCounterparty } from "./sweepCounterparty";
import { SweepSchedule } from "./sweepSchedule";
import { TokenAuthentication } from "./tokenAuthentication";
import { ValidationFacts } from "./validationFacts";
import { VerificationDeadline } from "./verificationDeadline";
import { VerificationError } from "./verificationError";
import { VerificationErrorRecursive } from "./verificationErrorRecursive";
import { Wallet } from "./wallet";
/* tslint:disable:no-unused-variable */
let primitives = [
"string",
"boolean",
"double",
"integer",
"long",
"float",
"number",
"any"
];
let enumsMap: Set<string> = new Set<string>([
"AccountHolder.StatusEnum",
"AccountHolderCapability.AllowedLevelEnum",
"AccountHolderCapability.RequestedLevelEnum",
"AccountHolderCapability.VerificationStatusEnum",
"AccountHolderNotificationRequest.TypeEnum",
"AccountSupportingEntityCapability.AllowedLevelEnum",
"AccountSupportingEntityCapability.RequestedLevelEnum",
"AccountSupportingEntityCapability.VerificationStatusEnum",
"BalanceAccount.StatusEnum",
"BalanceAccountNotificationRequest.TypeEnum",
"CapabilityProblemEntity.TypeEnum",
"CapabilityProblemEntityRecursive.TypeEnum",
"CapabilitySettings.FundingSourceEnum",
"CapabilitySettings.IntervalEnum",
"Card.FormFactorEnum",
"CardOrderItemDeliveryStatus.StatusEnum",
"CardOrderNotificationRequest.TypeEnum",
"IbanAccountIdentification.TypeEnum",
"NetworkTokenNotificationRequest.TypeEnum",
"PaymentInstrument.StatusEnum",
"PaymentInstrument.StatusReasonEnum",
"PaymentInstrument.TypeEnum",
"PaymentInstrumentAdditionalBankAccountIdentificationsInner.TypeEnum",
"PaymentNotificationRequest.TypeEnum",
"Phone.TypeEnum",
"PhoneNumber.PhoneTypeEnum",
"ScoreNotificationRequest.TypeEnum",
"SweepConfigurationNotificationRequest.TypeEnum",
"SweepConfigurationV2.CategoryEnum",
"SweepConfigurationV2.PrioritiesEnum",
"SweepConfigurationV2.ReasonEnum",
"SweepConfigurationV2.StatusEnum",
"SweepConfigurationV2.TypeEnum",
"SweepSchedule.TypeEnum",
"ValidationFacts.ResultEnum",
"VerificationDeadline.CapabilitiesEnum",
"VerificationError.CapabilitiesEnum",
"VerificationError.TypeEnum",
"VerificationErrorRecursive.CapabilitiesEnum",
"VerificationErrorRecursive.TypeEnum",
"Wallet.RecommendationReasonsEnum",
]);
let typeMap: {[index: string]: any} = {
"AccountHolder": AccountHolder,
"AccountHolderCapability": AccountHolderCapability,
"AccountHolderNotificationData": AccountHolderNotificationData,
"AccountHolderNotificationRequest": AccountHolderNotificationRequest,
"AccountSupportingEntityCapability": AccountSupportingEntityCapability,
"Address": Address,
"Amount": Amount,
"Authentication": Authentication,
"Balance": Balance,
"BalanceAccount": BalanceAccount,
"BalanceAccountNotificationData": BalanceAccountNotificationData,
"BalanceAccountNotificationRequest": BalanceAccountNotificationRequest,
"BalancePlatformNotificationResponse": BalancePlatformNotificationResponse,
"BankAccountDetails": BankAccountDetails,
"BankScoreSignalTriggeredData": BankScoreSignalTriggeredData,
"BulkAddress": BulkAddress,
"CapabilityProblem": CapabilityProblem,
"CapabilityProblemEntity": CapabilityProblemEntity,
"CapabilityProblemEntityRecursive": CapabilityProblemEntityRecursive,
"CapabilitySettings": CapabilitySettings,
"Card": Card,
"CardConfiguration": CardConfiguration,
"CardOrderItem": CardOrderItem,
"CardOrderItemDeliveryStatus": CardOrderItemDeliveryStatus,
"CardOrderNotificationRequest": CardOrderNotificationRequest,
"ContactDetails": ContactDetails,
"DeliveryAddress": DeliveryAddress,
"DeliveryContact": DeliveryContact,
"Device": Device,
"Expiry": Expiry,
"IbanAccountIdentification": IbanAccountIdentification,
"Name": Name,
"NetworkTokenNotificationDataV2": NetworkTokenNotificationDataV2,
"NetworkTokenNotificationRequest": NetworkTokenNotificationRequest,
"NetworkTokenRequestor": NetworkTokenRequestor,
"NetworkTokenRiskRuleData": NetworkTokenRiskRuleData,
"NetworkTokenRiskRuleSource": NetworkTokenRiskRuleSource,
"NetworkTokenTransactionRulesResult": NetworkTokenTransactionRulesResult,
"NetworkTokenTriggeredRiskRule": NetworkTokenTriggeredRiskRule,
"PaymentInstrument": PaymentInstrument,
"PaymentInstrumentAdditionalBankAccountIdentificationsInner": PaymentInstrumentAdditionalBankAccountIdentificationsInnerClass,
"PaymentInstrumentNotificationData": PaymentInstrumentNotificationData,
"PaymentNotificationRequest": PaymentNotificationRequest,
"Phone": Phone,
"PhoneNumber": PhoneNumber,
"PlatformPaymentConfiguration": PlatformPaymentConfiguration,
"RemediatingAction": RemediatingAction,
"Resource": Resource,
"ResourceReference": ResourceReference,
"ScoreNotificationRequest": ScoreNotificationRequest,
"SweepConfigurationNotificationData": SweepConfigurationNotificationData,
"SweepConfigurationNotificationRequest": SweepConfigurationNotificationRequest,
"SweepConfigurationV2": SweepConfigurationV2,
"SweepCounterparty": SweepCounterparty,
"SweepSchedule": SweepSchedule,
"TokenAuthentication": TokenAuthentication,
"ValidationFacts": ValidationFacts,
"VerificationDeadline": VerificationDeadline,
"VerificationError": VerificationError,
"VerificationErrorRecursive": VerificationErrorRecursive,
"Wallet": Wallet,
}
type MimeTypeDescriptor = {
type: string;
subtype: string;
subtypeTokens: string[];
};
/**
* Every mime-type consists of a type, subtype, and optional parameters.
* The subtype can be composite, including information about the content format.
* For example: `application/json-patch+json`, `application/merge-patch+json`.
*
* This helper transforms a string mime-type into an internal representation.
* This simplifies the implementation of predicates that in turn define common rules for parsing or stringifying
* the payload.
*/
const parseMimeType = (mimeType: string): MimeTypeDescriptor => {
const [type = '', subtype = ''] = mimeType.split('/');
return {
type,
subtype,
subtypeTokens: subtype.split('+'),
};
};
type MimeTypePredicate = (mimeType: string) => boolean;
// This factory creates a predicate function that checks a string mime-type against defined rules.
const mimeTypePredicateFactory = (predicate: (descriptor: MimeTypeDescriptor) => boolean): MimeTypePredicate => (mimeType) => predicate(parseMimeType(mimeType));
// Use this factory when you need to define a simple predicate based only on type and, if applicable, subtype.
const mimeTypeSimplePredicateFactory = (type: string, subtype?: string): MimeTypePredicate => mimeTypePredicateFactory((descriptor) => {
if (descriptor.type !== type) return false;
if (subtype != null && descriptor.subtype !== subtype) return false;
return true;
});
// Creating a set of named predicates that will help us determine how to handle different mime-types
const isTextLikeMimeType = mimeTypeSimplePredicateFactory('text');
const isJsonMimeType = mimeTypeSimplePredicateFactory('application', 'json');
const isJsonLikeMimeType = mimeTypePredicateFactory((descriptor) => descriptor.type === 'application' && descriptor.subtypeTokens.some((item) => item === 'json'));
const isOctetStreamMimeType = mimeTypeSimplePredicateFactory('application', 'octet-stream');
const isFormUrlencodedMimeType = mimeTypeSimplePredicateFactory('application', 'x-www-form-urlencoded');
// Defining a list of mime-types in the order of prioritization for handling.
const supportedMimeTypePredicatesWithPriority: MimeTypePredicate[] = [
isJsonMimeType,
isJsonLikeMimeType,
isTextLikeMimeType,
isOctetStreamMimeType,
isFormUrlencodedMimeType,
];
const nullableSuffix = " | null";
const optionalSuffix = " | undefined";
const arrayPrefix = "Array<";
const arraySuffix = ">";
const mapPrefix = "{ [key: string]: ";
const mapSuffix = "; }";
export class ObjectSerializer {
public static findCorrectType(data: any, expectedType: string) {
if (data == undefined) {
return expectedType;
} else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) {
return expectedType;
} else if (expectedType === "Date") {
return expectedType;
} else {
if (enumsMap.has(expectedType)) {
return expectedType;
}
if (!typeMap[expectedType]) {
return expectedType; // w/e we don't know the type
}
// Check the discriminator
let discriminatorProperty = typeMap[expectedType].discriminator;
if (discriminatorProperty == null) {
return expectedType; // the type does not have a discriminator. use it.
} else {
if (data[discriminatorProperty]) {
var discriminatorType = data[discriminatorProperty];
let mapping = typeMap[expectedType].mapping;
if (mapping != undefined && mapping[discriminatorType]) {
return mapping[discriminatorType]; // use the type given in the discriminator
} else if(typeMap[discriminatorType]) {
return discriminatorType;
} else {
return expectedType; // discriminator did not map to a type
}
} else {
return expectedType; // discriminator was not present (or an empty string)
}
}
}
}
/**
* Serializes a value into a plain JSON-compatible object based on its type.
*
* Supports primitives, arrays, maps, dates, enums, and classes defined in `typeMap`.
* Falls back to raw data if type is unknown or lacks `getAttributeTypeMap()`.
*
* @param data - The value to serialize.
* @param type - The expected type name as a string.
* @param format - Format hint (e.g. "date" or "date-time"). Default is an empty string.
* @returns A JSON-compatible representation of `data`.
*/
public static serialize(data: any, type: string, format: string = ""): any {
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.endsWith(nullableSuffix)) {
let subType: string = type.slice(0, -nullableSuffix.length); // Type | null => Type
return ObjectSerializer.serialize(data, subType, format);
} else if (type.endsWith(optionalSuffix)) {
let subType: string = type.slice(0, -optionalSuffix.length); // Type | undefined => Type
return ObjectSerializer.serialize(data, subType, format);
} else if (type.startsWith(arrayPrefix)) {
let subType: string = type.slice(arrayPrefix.length, -arraySuffix.length); // Array<Type> => Type
let transformedData: any[] = [];
for (let date of data) {
transformedData.push(ObjectSerializer.serialize(date, subType, format));
}
return transformedData;
} else if (type.startsWith(mapPrefix)) {
let subType: string = type.slice(mapPrefix.length, -mapSuffix.length); // { [key: string]: Type; } => Type
let transformedData: { [key: string]: any } = {};
for (let key in data) {
transformedData[key] = ObjectSerializer.serialize(
data[key],
subType,
format,
);
}
return transformedData;
} else if (type === "Date") {
if (format == "date") {
let month = data.getMonth()+1
month = month < 10 ? "0" + month.toString() : month.toString()
let day = data.getDate();
day = day < 10 ? "0" + day.toString() : day.toString();
return data.getFullYear() + "-" + month + "-" + day;
} else {
return data.toISOString();
}
} else {
if (enumsMap.has(type)) {
return data;
}
if (!typeMap[type]) { // in case we dont know the type
return data;
}
// Get the actual type of this object
type = this.findCorrectType(data, type);
const clazz = typeMap[type];
// Safe check for getAttributeTypeMap
if (typeof clazz.getAttributeTypeMap !== "function") {
return { ...data }; // fallback: shallow copy
}
// get the map for the correct type.
let attributeTypes = typeMap[type].getAttributeTypeMap();
let instance: {[index: string]: any} = {};
for (let attributeType of attributeTypes) {
instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type, attributeType.format);
}
return instance;
}
}
/**
* Deserializes a plain JSON-compatible object into a typed instance.
*
* Handles primitives, arrays, maps, dates, enums, and known classes from `typeMap`.
* Uses discriminators when available to resolve polymorphic types.
* Falls back to raw data if the type is unknown or lacks `getAttributeTypeMap()`.
*
* @param data - The raw input to deserialize.
* @param type - The expected type name as a string.
* @param format - Format hint (e.g. "date" or "date-time"). Default is an empty string.
* @returns A deserialized instance or value of `data`.
*/
public static deserialize(data: any, type: string, format: string = ""): any {
// polymorphism may change the actual type.
type = ObjectSerializer.findCorrectType(data, type);
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.endsWith(nullableSuffix)) {
let subType: string = type.slice(0, -nullableSuffix.length); // Type | null => Type
return ObjectSerializer.deserialize(data, subType, format);
} else if (type.endsWith(optionalSuffix)) {
let subType: string = type.slice(0, -optionalSuffix.length); // Type | undefined => Type
return ObjectSerializer.deserialize(data, subType, format);
} else if (type.startsWith(arrayPrefix)) {
let subType: string = type.slice(arrayPrefix.length, -arraySuffix.length); // Array<Type> => Type
let transformedData: any[] = [];
for (let date of data) {
transformedData.push(ObjectSerializer.deserialize(date, subType, format));
}
return transformedData;
} else if (type.startsWith(mapPrefix)) {
let subType: string = type.slice(mapPrefix.length, -mapSuffix.length); // { [key: string]: Type; } => Type
let transformedData: { [key: string]: any } = {};
for (let key in data) {
transformedData[key] = ObjectSerializer.deserialize(
data[key],
subType,
format,
);
}
return transformedData;
} else if (type === "Date") {
return new Date(data);
} else {
if (enumsMap.has(type)) {// is Enum
return data;
}
if (!typeMap[type]) { // dont know the type
return data;
}
let instance = new typeMap[type]();
// Safe check for getAttributeTypeMap
if (typeof typeMap[type].getAttributeTypeMap !== "function") {
Object.assign(instance, data); // fallback: shallow copy
return instance;
}
let attributeTypes = typeMap[type].getAttributeTypeMap();
for (let attributeType of attributeTypes) {
let value = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type, attributeType.format);
if (value !== undefined) {
instance[attributeType.name] = value;
}
}
return instance;
}
}
/**
* Normalize media type
*
* We currently do not handle any media types attributes, i.e. anything
* after a semicolon. All content is assumed to be UTF-8 compatible.
*/
public static normalizeMediaType(mediaType: string | undefined): string | undefined {
if (mediaType === undefined) {
return undefined;
}
return (mediaType.split(";")[0] ?? '').trim().toLowerCase();
}
/**
* From a list of possible media types, choose the one we can handle best.
*
* The order of the given media types does not have any impact on the choice
* made.
*/
public static getPreferredMediaType(mediaTypes: Array<string>): string {
/** According to OAS 3 we should default to json */
if (mediaTypes.length === 0) {
return "application/json";
}
const normalMediaTypes = mediaTypes.map(ObjectSerializer.normalizeMediaType);
for (const predicate of supportedMimeTypePredicatesWithPriority) {
for (const mediaType of normalMediaTypes) {
if (mediaType != null && predicate(mediaType)) {
return mediaType;
}
}
}
throw new Error("None of the given media types are supported: " + mediaTypes.join(", "));
}
/**
* Convert data to a string according the given media type
*/
public static stringify(data: any, mediaType: string): string {
if (isTextLikeMimeType(mediaType)) {
return String(data);
}
if (isJsonLikeMimeType(mediaType)) {
return JSON.stringify(data);
}
throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.stringify.");
}
/**
* Parse data from a string according to the given media type
*/
public static parse(rawData: string, mediaType: string | undefined) {
if (mediaType === undefined) {
throw new Error("Cannot parse content. No Content-Type defined.");
}
if (isTextLikeMimeType(mediaType)) {
return rawData;
}
if (isJsonLikeMimeType(mediaType)) {
return JSON.parse(rawData);
}
throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.parse.");
}
}