UNPKG

2.77 kBPlain TextView Raw
1// Copyright IBM Corp. and LoopBack contributors 2018,2020. All Rights Reserved.
2// Node module: @loopback/rest
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6import debugModule from 'debug';
7const debug = debugModule('loopback:rest:coercion');
8
9/**
10 * Options for function coerceDatetime
11 */
12export type DateCoercionOptions = {
13 dateOnly?: boolean;
14};
15
16/**
17 * Options for function coerceInteger
18 */
19export type IntegerCoercionOptions = {
20 isLong?: boolean;
21};
22
23export function isEmpty(data: string) {
24 const result = data === '';
25 debug('isEmpty(%j) -> %s', data, result);
26 return result;
27}
28/**
29 * A set of truthy values. A data in this set will be coerced to `true`.
30 *
31 * @param data - The raw data get from http request
32 * @returns The corresponding coerced boolean type
33 */
34export function isTrue(data: string): boolean {
35 return ['TRUE', '1'].includes(data.toUpperCase());
36}
37
38/**
39 * A set of falsy values. A data in this set will be coerced to `false`.
40 * @param data - The raw data get from http request
41 * @returns The corresponding coerced boolean type
42 */
43export function isFalse(data: string): boolean {
44 return ['FALSE', '0'].includes(data.toUpperCase());
45}
46
47/**
48 * Return false for invalid date
49 */
50export function isValidDateTime(data: Date) {
51 return isNaN(data.getTime()) ? false : true;
52}
53
54const REGEX_RFC3339_DATE =
55 /^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])$/;
56
57/**
58 * Return true when a date follows the RFC3339 standard
59 *
60 * @param date - The date to verify
61 */
62export function matchDateFormat(date: string) {
63 const pattern = new RegExp(REGEX_RFC3339_DATE);
64 const result = pattern.test(date);
65 debug('matchDateFormat(%j) -> %s', date, result);
66 return result;
67}
68
69/**
70 * Return the corresponding OpenAPI data type given an OpenAPI schema
71 *
72 * @param type - The type in an OpenAPI schema specification
73 * @param format - The format in an OpenAPI schema specification
74 */
75export function getOAIPrimitiveType(type?: string, format?: string) {
76 if (type === 'object' || type === 'array') return type;
77 if (type === 'string') {
78 switch (format) {
79 case 'byte':
80 return 'byte';
81 case 'binary':
82 return 'binary';
83 case 'date':
84 return 'date';
85 case 'date-time':
86 return 'date-time';
87 case 'password':
88 return 'password';
89 default:
90 return 'string';
91 }
92 }
93 if (type === 'boolean') return 'boolean';
94 if (type === 'number')
95 switch (format) {
96 case 'float':
97 return 'float';
98 case 'double':
99 return 'double';
100 default:
101 return 'number';
102 }
103 if (type === 'integer') return format === 'int64' ? 'long' : 'integer';
104}