deno.land / x / urlcat@v3.1.0 / src / index.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
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
import qs, { IStringifyOptions } from 'qs';
// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport type ParamMap = Record<string, any>;export type UrlCatConfiguration = Partial<Pick<IStringifyOptions, 'arrayFormat'> & { objectFormat: Partial<Pick<IStringifyOptions, 'format'>> }>
/** * Builds a URL using the base template and specified parameters. * * @param {String} baseTemplate a URL template that contains zero or more :params * @param {Object} params an object with properties that correspond to the :params * in the base template. Unused properties become query params. * * @returns {String} a URL with path params substituted and query params appended * * @example * ```ts * urlcat('http://api.example.com/users/:id', { id: 42, search: 'foo' }) * // -> 'http://api.example.com/users/42?search=foo * ``` */export default function urlcat(baseTemplate: string, params: ParamMap): string;
/** * Concatenates the base URL and the path specified using '/' as a separator. * If a '/' occurs at the concatenation boundary in either parameter, it is removed. * * @param {String} baseUrl the first part of the URL * @param {String} path the second part of the URL * * @returns {String} the result of the concatenation * * @example * ```ts * urlcat('http://api.example.com/', '/users') * // -> 'http://api.example.com/users * ``` */export default function urlcat(baseUrl: string, path: string): string;
/** * Concatenates the base URL and the path specified using '/' as a separator. * If a '/' occurs at the concatenation boundary in either parameter, it is removed. * Substitutes path parameters with the properties of the @see params object and appends * unused properties in the path as query params. * * @param {String} baseUrl the first part of the URL * @param {String} path the second part of the URL * @param {Object} params Object with properties that correspond to the :params * in the base template. Unused properties become query params. * * @returns {String} URL with path params substituted and query params appended * * @example * ```ts * urlcat('http://api.example.com/', '/users/:id', { id: 42, search: 'foo' }) * // -> 'http://api.example.com/users/42?search=foo * ``` */export default function urlcat( baseUrl: string, pathTemplate: string, params: ParamMap): string;
/** * Concatenates the base URL and the path specified using '/' as a separator. * If a '/' occurs at the concatenation boundary in either parameter, it is removed. * Substitutes path parameters with the properties of the @see params object and appends * unused properties in the path as query params. * * @param {String} baseUrl the first part of the URL * @param {String} path the second part of the URL * @param {Object} params Object with properties that correspond to the :params * in the base template. Unused properties become query params. * @param {Object} config urlcat configuration object * * @returns {String} URL with path params substituted and query params appended * * @example * ```ts * urlcat('http://api.example.com/', '/users/:id', { id: 42, search: 'foo' }, {objectFormat: {format: 'RFC1738'}}) * // -> 'http://api.example.com/users/42?search=foo * ``` */export default function urlcat( baseUrlOrTemplate: string, pathTemplateOrParams: string | ParamMap, maybeParams: ParamMap, config: UrlCatConfiguration): string;
export default function urlcat( baseUrlOrTemplate: string, pathTemplateOrParams: string | ParamMap, maybeParams: ParamMap = {}, config: UrlCatConfiguration = {}): string { if (typeof pathTemplateOrParams === 'string') { const baseUrl = baseUrlOrTemplate; const pathTemplate = pathTemplateOrParams; const params = maybeParams; return urlcatImpl(pathTemplate, params, baseUrl, config); } else { const baseTemplate = baseUrlOrTemplate; const params = pathTemplateOrParams; return urlcatImpl(baseTemplate, params, undefined, config); }}
/** * Factory function providing a pre configured urlcat function * * @param {Object} config Configuration object for urlcat * * @returns {Function} urlcat decorator function * * @example * ```ts * configure({arrayFormat: 'brackets', objectFormat: {format: 'RFC1738'}}) * ``` */export function configure(rootConfig: UrlCatConfiguration) { return ( baseUrlOrTemplate: string, pathTemplateOrParams: string | ParamMap, maybeParams: ParamMap = {}, config: UrlCatConfiguration = {} ): string => urlcat(baseUrlOrTemplate, pathTemplateOrParams, maybeParams, { ...rootConfig, ...config });}
function joinFullUrl(renderedPath: string, baseUrl: string, pathAndQuery: string): string { if (renderedPath.length) { return join(baseUrl, '/', pathAndQuery); } else { return join(baseUrl, '?', pathAndQuery); }}
function urlcatImpl( pathTemplate: string, params: ParamMap, baseUrl: string | undefined, config: UrlCatConfiguration) { const { renderedPath, remainingParams } = path(pathTemplate, params); const cleanParams = removeNullOrUndef(remainingParams); const renderedQuery = query(cleanParams, config); const pathAndQuery = join(renderedPath, '?', renderedQuery);
return baseUrl ? joinFullUrl(renderedPath, baseUrl, pathAndQuery) : pathAndQuery;}
/** * Creates a query string from the specified object. * * @param {Object} params an object to convert into a query string. * @param {Object} config configuration to stringify the query params. * * @returns {String} Query string. * * @example * ```ts * query({ id: 42, search: 'foo' }) * // -> 'id=42&search=foo' * ``` */export function query(params: ParamMap, config?: UrlCatConfiguration): string { /* NOTE: Handle quirk of `new UrlSearchParams(params).toString()` in Webkit 602.x.xx * versions which returns stringified object when params is empty object */ if (Object.keys(params).length < 1) { return '' }
const qsConfiguration: IStringifyOptions = { format: config?.objectFormat?.format ?? 'RFC1738', // RDC1738 is urlcat's current default. Breaking change if default is changed arrayFormat: config?.arrayFormat }
return qs.stringify(params, qsConfiguration);}
/** * Substitutes :params in a template with property values of an object. * * @param {String} template a string that contains :params. * @param {Object} params an object with keys that correspond to the params in the template. * * @returns {String} Rendered path after substitution. * * @example * ```ts * subst('/users/:id/posts/:postId', { id: 42, postId: 36 }) * // -> '/users/42/posts/36' * ``` */export function subst(template: string, params: ParamMap): string { const { renderedPath } = path(template, params); return renderedPath;}
function path(template: string, params: ParamMap) { const remainingParams = { ...params };
const renderedPath = template.replace(/:[_A-Za-z]+[_A-Za-z0-9]*/g, p => { // do not replace "::" const key = p.slice(1); validatePathParam(params, key); delete remainingParams[key]; return encodeURIComponent(params[key]); });
return { renderedPath, remainingParams };}
function validatePathParam(params: ParamMap, key: string) { const allowedTypes = ['boolean', 'string', 'number'];
if (!Object.prototype.hasOwnProperty.call(params, key)) { throw new Error(`Missing value for path parameter ${key}.`); } if (!allowedTypes.includes(typeof params[key])) { throw new TypeError( `Path parameter ${key} cannot be of type ${typeof params[key]}. ` + `Allowed types are: ${allowedTypes.join(', ')}.` ); } if (typeof params[key] === 'string' && params[key].trim() === '') { throw new Error(`Path parameter ${key} cannot be an empty string.`); }}
/** * Joins two strings using a separator. * If the separator occurs at the concatenation boundary in either of the strings, it is removed. * This prevents accidental duplication of the separator. * * @param {String} part1 First string. * @param {String} separator Separator used for joining. * @param {String} part2 Second string. * * @returns {String} Joined string. * * @example * ```ts * join('first/', '/', '/second') * // -> 'first/second' * ``` */export function join(part1: string, separator: string, part2: string): string { const p1 = part1.endsWith(separator) ? part1.slice(0, -separator.length) : part1; const p2 = part2.startsWith(separator) ? part2.slice(separator.length) : part2; return p1 === '' || p2 === '' ? p1 + p2 : p1 + separator + p2;}
function removeNullOrUndef(params: ParamMap) { return Object.keys(params) .filter(k => notNullOrUndefined(params[k])) .reduce((result, k) => { result[k] = params[k]; return result; }, {} as ParamMap);}
function notNullOrUndefined(v: string) { return v !== undefined && v !== null;}
urlcat

Version Info

Tagged at
a year ago