Skip to content

Commit 13ecfbd

Browse files
author
svolkov
committed
feat: better route naming when operationId not existed
1 parent ab9c11e commit 13ecfbd

File tree

8 files changed

+63
-32
lines changed

8 files changed

+63
-32
lines changed

src/routes.js

Lines changed: 39 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,14 @@ const _ = require("lodash");
22
const { parseSchema } = require("./schema");
33
const { inlineExtraFormatters } = require("./typeFormatters");
44

5+
const methodAliases = {
6+
get: (pathName, hasPathInserts) => _.camelCase(`${pathName}_${hasPathInserts ? 'detail': 'list'}`),
7+
post: (pathName, hasPathInserts) => _.camelCase(`${pathName}_create`),
8+
put: (pathName, hasPathInserts) => _.camelCase(`${pathName}_update`),
9+
patch: (pathName, hasPathInserts) => _.camelCase(`${pathName}_partial_update`),
10+
delete: (pathName, hasPathInserts) => _.camelCase(`${pathName}_delete`)
11+
}
12+
513
const getTypeFromRequestInfo = (requestInfo, parsedSchemas, contentType) => {
614
// TODO: make more flexible pick schema without content type
715
const schema = _.get(requestInfo, `content["${contentType}"].schema`);
@@ -20,14 +28,17 @@ const findSuccessResponse = (responses) => {
2028
return _.find(responses, (v, status) => status === 'default' || (+status >= 200 && +status < 300))
2129
}
2230

31+
const createCustomOperationId = (method, route, moduleName) => {
32+
const hasPathInserts = /\{(\w){1,}\}/g.test(route);
33+
const splitedRouteBySlash = _.replace(route, /\{(\w){1,}\}/g, '').split('/').filter(Boolean);
34+
const routeParts = (splitedRouteBySlash.length > 1 ? splitedRouteBySlash.splice(1) : splitedRouteBySlash).join('_');
35+
return routeParts.length > 3 && methodAliases[method] ? methodAliases[method](routeParts, hasPathInserts) : _.camelCase(_.lowerCase(method) + '_' + ([moduleName]).join('_')) || 'index'
36+
}
37+
2338
const getRouteName = (operationId, method, route, moduleName) => {
2439
if (operationId) return operationId;
2540
if (route === '/') return `${_.lowerCase(method)}Root`;
26-
27-
const routeParts = _.replace(route, /\{(\w){1,}\}/g, '').split('/').filter(Boolean);
28-
29-
// create route name via method and route
30-
return _.camelCase(_.lowerCase(method) + '_' + (moduleName ? routeParts.splice(1) : routeParts).join('_')) || 'index'
41+
return createCustomOperationId(method, route, moduleName);
3142
}
3243

3344
const parseRoutes = (routes, parsedSchemas) =>
@@ -159,7 +170,7 @@ const groupRoutes = routes => {
159170
`🥵 This method has been renamed to "${route.name + (duplicates[route.moduleName][route.name] + 1)}()" to solve conflict names.`
160171
)
161172
route.comments.push(`@originalName ${route.name}`)
162-
route.comments.push(`@duplicate true`)
173+
route.comments.push(`@duplicate`)
163174
route.name += ++duplicates[route.moduleName][route.name];
164175
}
165176

@@ -171,21 +182,37 @@ const groupRoutes = routes => {
171182
return modules
172183
}, {
173184
$outOfModule: []
174-
}), (shuffle, packRoutes, moduleName) => {
175-
185+
}), (acc, packRoutes, moduleName) => {
186+
187+
// if (moduleName === "$outOfModule") {
188+
// acc.outOfModule.push(...routes)
189+
// } else {
190+
// if (routes.length === 1) {
191+
// const route = routes[0]
192+
// acc.outOfModule.push({
193+
// ...route,
194+
// name: route.name === _.lowerCase(route.name) ? moduleName : route.name,
195+
// })
196+
// } else {
197+
// acc.combined.push({
198+
// moduleName,
199+
// routes: routes,
200+
// })
201+
// }
202+
// }
176203

177204
if (moduleName === "$outOfModule") {
178-
shuffle['outOfModule'] = packRoutes
205+
acc.outOfModule = packRoutes
179206
} else {
180-
if (!shuffle.combined) shuffle.combined = []
207+
if (!acc.combined) acc.combined = []
181208

182-
shuffle.combined.push({
209+
acc.combined.push({
183210
moduleName,
184211
routes: packRoutes,
185212
})
186213
}
187214

188-
return shuffle;
215+
return acc;
189216
}, {})
190217
}
191218

tests/generated/v2.0/petstore-minimal.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,11 @@ export class Api<SecurityDataType> {
100100

101101

102102
/**
103-
* @name get
103+
* @name petsList
104104
* @request GET:/pets
105105
* @description Returns all pets from the system that the user has access to
106106
*/
107-
get: (params?: RequestParams) =>
107+
petsList: (params?: RequestParams) =>
108108
this.request<Pet[]>(`/pets`, "GET", params, null),
109109
}
110110

tests/generated/v2.0/uber.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -196,63 +196,63 @@ export class Api<SecurityDataType> {
196196

197197
/**
198198
* @tags Products
199-
* @name get
199+
* @name productsList
200200
* @summary Product Types
201201
* @request GET:/products
202202
* @secure
203203
* @description The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order.
204204
*/
205-
get: (query: { latitude: number, longitude: number }, params?: RequestParams) =>
205+
productsList: (query: { latitude: number, longitude: number }, params?: RequestParams) =>
206206
this.request<Product[]>(`/products${this.addQueryParams(query)}`, "GET", params, null, true),
207207
}
208208
estimates = {
209209

210210

211211
/**
212212
* @tags Estimates
213-
* @name getPrice
213+
* @name priceList
214214
* @summary Price Estimates
215215
* @request GET:/estimates/price
216216
* @description The Price Estimates endpoint returns an estimated price range for each product offered at a given location. The price estimate is provided as a formatted string with the full price range and the localized currency symbol.<br><br>The response also includes low and high estimates, and the [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for situations requiring currency conversion. When surge is active for a particular product, its surge_multiplier will be greater than 1, but the price estimate already factors in this multiplier.
217217
*/
218-
getPrice: (query: { start_latitude: number, start_longitude: number, end_latitude?: number, end_longitude: number }, params?: RequestParams) =>
218+
priceList: (query: { start_latitude: number, start_longitude: number, end_latitude?: number, end_longitude: number }, params?: RequestParams) =>
219219
this.request<PriceEstimate[]>(`/estimates/price${this.addQueryParams(query)}`, "GET", params, null),
220220

221221

222222
/**
223223
* @tags Estimates
224-
* @name getTime
224+
* @name timeList
225225
* @summary Time Estimates
226226
* @request GET:/estimates/time
227227
* @description The Time Estimates endpoint returns ETAs for all products offered at a given location, with the responses expressed as integers in seconds. We recommend that this endpoint be called every minute to provide the most accurate, up-to-date ETAs.
228228
*/
229-
getTime: (query: { start_latitude: number, start_longitude: number, customer_uuid?: string, product_id?: string }, params?: RequestParams) =>
229+
timeList: (query: { start_latitude: number, start_longitude: number, customer_uuid?: string, product_id?: string }, params?: RequestParams) =>
230230
this.request<Product[]>(`/estimates/time${this.addQueryParams(query)}`, "GET", params, null),
231231
}
232232
me = {
233233

234234

235235
/**
236236
* @tags User
237-
* @name get
237+
* @name getMe
238238
* @summary User Profile
239239
* @request GET:/me
240240
* @description The User Profile endpoint returns information about the Uber user that has authorized with the application.
241241
*/
242-
get: (params?: RequestParams) =>
242+
getMe: (params?: RequestParams) =>
243243
this.request<Profile>(`/me`, "GET", params, null),
244244
}
245245
history = {
246246

247247

248248
/**
249249
* @tags User
250-
* @name get
250+
* @name historyList
251251
* @summary User Activity
252252
* @request GET:/history
253253
* @description The User Activity endpoint returns data about a user's lifetime activity with Uber. The response will include pickup locations and times, dropoff locations and times, the distance of past requests, and information about which products were requested.<br><br>The history array in the response will have a maximum length based on the limit parameter. The response value count may exceed limit, therefore subsequent API requests may be necessary.
254254
*/
255-
get: (query: { offset?: number, limit?: number }, params?: RequestParams) =>
255+
historyList: (query: { offset?: number, limit?: number }, params?: RequestParams) =>
256256
this.request<Activities>(`/history${this.addQueryParams(query)}`, "GET", params, null),
257257
}
258258

tests/generated/v3.0/allof-example.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,10 +102,10 @@ export class Api<SecurityDataType> {
102102

103103

104104
/**
105-
* @name patch
105+
* @name petsPartialUpdate
106106
* @request PATCH:/pets
107107
*/
108-
patch: (data: Cat | Dog, params?: RequestParams) =>
108+
petsPartialUpdate: (data: Cat | Dog, params?: RequestParams) =>
109109
this.request<any>(`/pets`, "PATCH", params, data),
110110
}
111111

tests/generated/v3.0/anyof-example.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,10 @@ export class Api<SecurityDataType> {
104104

105105

106106
/**
107-
* @name patch
107+
* @name petsPartialUpdate
108108
* @request PATCH:/pets
109109
*/
110-
patch: (data: PetByAge | PetByType | (PetByAge & PetByType), params?: RequestParams) =>
110+
petsPartialUpdate: (data: PetByAge | PetByType | (PetByAge & PetByType), params?: RequestParams) =>
111111
this.request<any>(`/pets`, "PATCH", params, data),
112112
}
113113

tests/generated/v3.0/callback-example.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,11 +104,11 @@ export class Api<SecurityDataType> {
104104

105105

106106
/**
107-
* @name post
107+
* @name streamsCreate
108108
* @request POST:/streams
109109
* @description subscribes a client to receive out-of-band data
110110
*/
111-
post: (query: { callbackUrl: string }, params?: RequestParams) =>
111+
streamsCreate: (query: { callbackUrl: string }, params?: RequestParams) =>
112112
this.request<{ subscriptionId: string }>(`/streams${this.addQueryParams(query)}`, "POST", params, null),
113113
}
114114

tests/generated/v3.0/oneof-example.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,10 @@ export class Api<SecurityDataType> {
104104

105105

106106
/**
107-
* @name patch
107+
* @name petsPartialUpdate
108108
* @request PATCH:/pets
109109
*/
110-
patch: (data: Cat | Dog, params?: RequestParams) =>
110+
petsPartialUpdate: (data: Cat | Dog, params?: RequestParams) =>
111111
this.request<any>(`/pets`, "PATCH", params, data),
112112
}
113113

tests/validate.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const v3ApiPaths = createGeneratedApiInfos(path.resolve(__dirname, "./generated/
1313
...v2ApiPaths,
1414
...v3ApiPaths,
1515
].forEach(path => {
16+
process.stdout.write(`validating ${path}: `)
1617
var program = tsc.createProgram([path], {
1718
noEmitOnError: true,
1819
noImplicitAny: false,
@@ -32,7 +33,10 @@ const v3ApiPaths = createGeneratedApiInfos(path.resolve(__dirname, "./generated/
3233
console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
3334
});
3435

36+
process.stdout.write(`errors ${emitResult.diagnostics.length}\r\n`)
3537
if (emitResult.diagnostics.length){
3638
process.exit(1)
3739
}
3840
})
41+
42+
console.log('everything is good:)')

0 commit comments

Comments
 (0)