From 947984dbf47dfe80345e963e1fdbef05c3ae7b52 Mon Sep 17 00:00:00 2001 From: sarankumar1325 <120080287+sarankumar1325@users.noreply.github.com> Date: Sat, 5 Dec 2026 10:59:19 +0530 Subject: [PATCH] fix(cli): pass the controller's own argument names to the service The generated controller implementation passed each OpenAPI parameter by its spec name, so a name that is not a valid identifier (pet-id, or the reserved word if) produced code that does not compile, while the method signature declares the escaped name (petId, _if). Pass the names the signature declares, including the request body's. Fixes #11937 Signed-off-by: sarankumar1325 <120080287+sarankumar1325@users.noreply.github.com> --- .../cli/generators/openapi/spec-helper.js | 16 ++---- .../openapi/controller-spec.unit.snapshots.js | 2 +- .../cli/test/unit/openapi/spec-helper.unit.js | 53 ++++++++++++++++++- 3 files changed, 57 insertions(+), 14 deletions(-) diff --git a/packages/cli/generators/openapi/spec-helper.js b/packages/cli/generators/openapi/spec-helper.js index 0295eabce303..bd9c8b602a52 100644 --- a/packages/cli/generators/openapi/spec-helper.js +++ b/packages/cli/generators/openapi/spec-helper.js @@ -213,6 +213,8 @@ function buildMethodSpec(controllerSpec, op, options) { let args = []; let interfaceArgs = []; const namedParameters = []; + // The controller's own argument names, which its implementation passes on + const implementationArgs = []; const parameters = op.spec.parameters; // Keep track of param names to avoid duplicates const paramNames = {}; @@ -220,6 +222,7 @@ function buildMethodSpec(controllerSpec, op, options) { if (parameters) { args = parameters.map(p => { const {paramType, argName} = buildParameter(p, paramNames, comments); + implementationArgs.push(argName); const paramJson = printSpecObject(p); const optionalType = !p.required ? ' | undefined' : ''; return `@param(${paramJson}) ${argName}: ${paramType.signature}${optionalType}`; @@ -268,6 +271,7 @@ function buildMethodSpec(controllerSpec, op, options) { args.push( `@requestBody(${bodySpecJson}) ${bodyParam}: ${bodyType.signature}`, ); + implementationArgs.push(bodyParam); interfaceArgs.push(`${bodyParam}: ${bodyType.signature}`); namedParameters.push({ paramName: 'requestBody', @@ -350,22 +354,12 @@ function buildMethodSpec(controllerSpec, op, options) { methodSpec.implementation = op.spec['x-implementation']; } if (!methodSpec.implementation) { - const methodParameters = {}; - methodParameters[methodName] = []; - if (parameters) { - parameters.forEach(param => { - methodParameters[methodName].push(param.name); - }); - } - if (op.spec.requestBody) { - methodParameters[methodName].push('_requestBody'); - } controllerSpec.serviceClassNameCamelCase = camelCase( controllerSpec.serviceClassName, ); methodSpec.implementation = `return this.${ controllerSpec.serviceClassNameCamelCase - }.${methodName}(${methodParameters[methodName].join(', ')});`; + }.${methodName}(${implementationArgs.join(', ')});`; } return methodSpec; diff --git a/packages/cli/snapshots/unit/openapi/controller-spec.unit.snapshots.js b/packages/cli/snapshots/unit/openapi/controller-spec.unit.snapshots.js index 2fed24c3c070..d9226ce54bc6 100644 --- a/packages/cli/snapshots/unit/openapi/controller-spec.unit.snapshots.js +++ b/packages/cli/snapshots/unit/openapi/controller-spec.unit.snapshots.js @@ -8,5 +8,5 @@ 'use strict'; exports[`openapi to controllers/models generates models for customer 1`] = ` -[{tag:'Customer',decoration:"@api({\\n components: {\\n schemas: {\\n Name: {\\n type: 'string',\\n },\\n profileId: {\\n type: 'string',\\n },\\n AddressList: {\\n items: {\\n $ref: '#/components/schemas/Address',\\n },\\n type: 'array',\\n },\\n Address: {\\n type: 'object',\\n properties: {\\n street: {\\n type: 'string',\\n },\\n city: {\\n type: 'string',\\n },\\n state: {\\n type: 'string',\\n },\\n zipCode: {\\n type: 'string',\\n },\\n },\\n additionalProperties: true,\\n },\\n USAddress: {\\n $ref: '#/components/schemas/Address',\\n },\\n Customer: {\\n required: [\\n 'id',\\n ],\\n properties: {\\n id: {\\n type: 'integer',\\n format: 'int64',\\n },\\n 'first-name': {\\n type: 'string',\\n },\\n 'last-name': {\\n $ref: '#/components/schemas/Name',\\n },\\n profiles: {\\n type: 'array',\\n items: {\\n $ref: '#/components/schemas/profileId',\\n },\\n },\\n emails: {\\n type: 'array',\\n items: {\\n type: 'string',\\n },\\n },\\n addresses: {\\n $ref: '#/components/schemas/AddressList',\\n },\\n 'us-office': {\\n $ref: '#/components/schemas/USAddress',\\n },\\n },\\n },\\n },\\n },\\n paths: {},\\n})",description:'Customer resource',className:'CustomerController',serviceClassName:'CustomerService',imports:["import {Customer} from '../models/customer.model';"],methodMapping:{getCustomers:'getCustomers',createCustomer:'createCustomer',findCustomerById:'find customer by id'},serviceClassNameCamelCase:'customerService',methods:[{description:'Returns all customers (/* customers */)',comments:['Returns all customers (/* customers */)','','@param _if if condition','@param limit maximum number of results to return','@param accessToken Access token (/* access_token */)','@returns customer response'],decoration:"@operation('get', '/customers', {\\n tags: [\\n 'Customer',\\n ],\\n description: 'Returns all customers (/* customers */)',\\n operationId: 'getCustomers',\\n parameters: [\\n {\\n name: 'if',\\n in: 'query',\\n description: 'if condition',\\n required: false,\\n style: 'form',\\n schema: {\\n type: 'array',\\n items: {\\n type: 'string',\\n },\\n },\\n },\\n {\\n name: 'limit',\\n in: 'query',\\n description: 'maximum number of results to return',\\n required: false,\\n schema: {\\n type: 'integer',\\n format: 'int32',\\n },\\n },\\n {\\n name: 'access-token',\\n in: 'query',\\n description: 'Access token (/* access_token */)',\\n required: false,\\n schema: {\\n type: 'string',\\n },\\n },\\n ],\\n responses: {\\n '200': {\\n description: 'customer response',\\n content: {\\n 'application/json': {\\n schema: {\\n type: 'array',\\n items: {\\n $ref: '#/components/schemas/Customer',\\n },\\n },\\n },\\n },\\n },\\n },\\n})",signature:"async getCustomers(@param({\\n name: 'if',\\n in: 'query',\\n description: 'if condition',\\n required: false,\\n style: 'form',\\n schema: {\\n type: 'array',\\n items: {\\n type: 'string',\\n },\\n },\\n}) _if: string[] | undefined, @param({\\n name: 'limit',\\n in: 'query',\\n description: 'maximum number of results to return',\\n required: false,\\n schema: {\\n type: 'integer',\\n format: 'int32',\\n },\\n}) limit: number | undefined, @param({\\n name: 'access-token',\\n in: 'query',\\n description: 'Access token (/* access_token */)',\\n required: false,\\n schema: {\\n type: 'string',\\n },\\n}) accessToken: string | undefined): Promise",signatureForInterface:'getCustomers(_if: string[] | undefined, limit: number | undefined, accessToken: string | undefined): Promise',signatureForNamedParams:"getCustomers(params: { if: string[]; limit: number; 'access-token': string }): Promise",implementation:'return this.customerService.getCustomers(if, limit, access-token);'},{description:'Creates a new customer',comments:['Creates a new customer','','@param accessToken Access token (/* access_token */)','@param _requestBody Customer to add','@returns customer response'],decoration:"@operation('post', '/customers', {\\n tags: [\\n 'Customer',\\n ],\\n description: 'Creates a new customer',\\n operationId: 'addCustomer',\\n 'x-operation-name': 'createCustomer',\\n requestBody: {\\n description: 'Customer to add',\\n required: true,\\n content: {\\n 'application/json': {\\n schema: {\\n $ref: '#/components/schemas/Customer',\\n },\\n },\\n },\\n },\\n responses: {\\n '200': {\\n description: 'customer response',\\n content: {\\n 'application/json': {\\n schema: {\\n $ref: '#/components/schemas/Customer',\\n },\\n },\\n },\\n },\\n },\\n parameters: [\\n {\\n name: 'access-token',\\n in: 'query',\\n description: 'Access token (/* access_token */)',\\n required: false,\\n schema: {\\n type: 'string',\\n },\\n },\\n ],\\n})",signature:"async createCustomer(@param({\\n name: 'access-token',\\n in: 'query',\\n description: 'Access token (/* access_token */)',\\n required: false,\\n schema: {\\n type: 'string',\\n },\\n}) accessToken: string | undefined, @requestBody({\\n description: 'Customer to add',\\n required: true,\\n content: {\\n 'application/json': {\\n schema: {\\n $ref: '#/components/schemas/Customer',\\n },\\n },\\n },\\n}) _requestBody: Customer): Promise",signatureForInterface:'createCustomer(accessToken: string | undefined, _requestBody: Customer): Promise',signatureForNamedParams:"createCustomer(params: { 'access-token': string; requestBody: Customer }): Promise",implementation:'return this.customerService.createCustomer(access-token, _requestBody);'},{description:'Returns a customer based on a single ID',comments:['Returns a customer based on a single ID','','@param customerId ID of customer to fetch','@returns customer response'],decoration:"@operation('get', '/customers/{customer_id}', {\\n tags: [\\n 'Customer',\\n ],\\n description: 'Returns a customer based on a single ID',\\n 'x-implementation': \\"return {id: customerId, 'first-name': 'John', 'last-name': 'Smith'};\\",\\n operationId: 'find customer by id',\\n parameters: [\\n {\\n name: 'customer-id',\\n in: 'path',\\n description: 'ID of customer to fetch',\\n required: true,\\n schema: {\\n type: 'integer',\\n format: 'int64',\\n },\\n },\\n ],\\n responses: {\\n '200': {\\n description: 'customer response',\\n content: {\\n 'application/json': {\\n schema: {\\n $ref: '#/components/schemas/Customer',\\n },\\n },\\n },\\n },\\n },\\n})",signature:"async findCustomerById(@param({\\n name: 'customer-id',\\n in: 'path',\\n description: 'ID of customer to fetch',\\n required: true,\\n schema: {\\n type: 'integer',\\n format: 'int64',\\n },\\n}) customerId: number): Promise",signatureForInterface:'findCustomerById(customerId: number): Promise',signatureForNamedParams:'findCustomerById(params: { customer_id: number }): Promise',implementation:"return {id: customerId, 'first-name': 'John', 'last-name': 'Smith'};"}],methodMappingObject:"{\\n getCustomers: 'getCustomers',\\n createCustomer: 'createCustomer',\\n findCustomerById: 'find customer by id',\\n}"}] +[{tag:'Customer',decoration:"@api({\\n components: {\\n schemas: {\\n Name: {\\n type: 'string',\\n },\\n profileId: {\\n type: 'string',\\n },\\n AddressList: {\\n items: {\\n $ref: '#/components/schemas/Address',\\n },\\n type: 'array',\\n },\\n Address: {\\n type: 'object',\\n properties: {\\n street: {\\n type: 'string',\\n },\\n city: {\\n type: 'string',\\n },\\n state: {\\n type: 'string',\\n },\\n zipCode: {\\n type: 'string',\\n },\\n },\\n additionalProperties: true,\\n },\\n USAddress: {\\n $ref: '#/components/schemas/Address',\\n },\\n Customer: {\\n required: [\\n 'id',\\n ],\\n properties: {\\n id: {\\n type: 'integer',\\n format: 'int64',\\n },\\n 'first-name': {\\n type: 'string',\\n },\\n 'last-name': {\\n $ref: '#/components/schemas/Name',\\n },\\n profiles: {\\n type: 'array',\\n items: {\\n $ref: '#/components/schemas/profileId',\\n },\\n },\\n emails: {\\n type: 'array',\\n items: {\\n type: 'string',\\n },\\n },\\n addresses: {\\n $ref: '#/components/schemas/AddressList',\\n },\\n 'us-office': {\\n $ref: '#/components/schemas/USAddress',\\n },\\n },\\n },\\n },\\n },\\n paths: {},\\n})",description:'Customer resource',className:'CustomerController',serviceClassName:'CustomerService',imports:["import {Customer} from '../models/customer.model';"],methodMapping:{getCustomers:'getCustomers',createCustomer:'createCustomer',findCustomerById:'find customer by id'},serviceClassNameCamelCase:'customerService',methods:[{description:'Returns all customers (/* customers */)',comments:['Returns all customers (/* customers */)','','@param _if if condition','@param limit maximum number of results to return','@param accessToken Access token (/* access_token */)','@returns customer response'],decoration:"@operation('get', '/customers', {\\n tags: [\\n 'Customer',\\n ],\\n description: 'Returns all customers (/* customers */)',\\n operationId: 'getCustomers',\\n parameters: [\\n {\\n name: 'if',\\n in: 'query',\\n description: 'if condition',\\n required: false,\\n style: 'form',\\n schema: {\\n type: 'array',\\n items: {\\n type: 'string',\\n },\\n },\\n },\\n {\\n name: 'limit',\\n in: 'query',\\n description: 'maximum number of results to return',\\n required: false,\\n schema: {\\n type: 'integer',\\n format: 'int32',\\n },\\n },\\n {\\n name: 'access-token',\\n in: 'query',\\n description: 'Access token (/* access_token */)',\\n required: false,\\n schema: {\\n type: 'string',\\n },\\n },\\n ],\\n responses: {\\n '200': {\\n description: 'customer response',\\n content: {\\n 'application/json': {\\n schema: {\\n type: 'array',\\n items: {\\n $ref: '#/components/schemas/Customer',\\n },\\n },\\n },\\n },\\n },\\n },\\n})",signature:"async getCustomers(@param({\\n name: 'if',\\n in: 'query',\\n description: 'if condition',\\n required: false,\\n style: 'form',\\n schema: {\\n type: 'array',\\n items: {\\n type: 'string',\\n },\\n },\\n}) _if: string[] | undefined, @param({\\n name: 'limit',\\n in: 'query',\\n description: 'maximum number of results to return',\\n required: false,\\n schema: {\\n type: 'integer',\\n format: 'int32',\\n },\\n}) limit: number | undefined, @param({\\n name: 'access-token',\\n in: 'query',\\n description: 'Access token (/* access_token */)',\\n required: false,\\n schema: {\\n type: 'string',\\n },\\n}) accessToken: string | undefined): Promise",signatureForInterface:'getCustomers(_if: string[] | undefined, limit: number | undefined, accessToken: string | undefined): Promise',signatureForNamedParams:"getCustomers(params: { if: string[]; limit: number; 'access-token': string }): Promise",implementation:'return this.customerService.getCustomers(_if, limit, accessToken);'},{description:'Creates a new customer',comments:['Creates a new customer','','@param accessToken Access token (/* access_token */)','@param _requestBody Customer to add','@returns customer response'],decoration:"@operation('post', '/customers', {\\n tags: [\\n 'Customer',\\n ],\\n description: 'Creates a new customer',\\n operationId: 'addCustomer',\\n 'x-operation-name': 'createCustomer',\\n requestBody: {\\n description: 'Customer to add',\\n required: true,\\n content: {\\n 'application/json': {\\n schema: {\\n $ref: '#/components/schemas/Customer',\\n },\\n },\\n },\\n },\\n responses: {\\n '200': {\\n description: 'customer response',\\n content: {\\n 'application/json': {\\n schema: {\\n $ref: '#/components/schemas/Customer',\\n },\\n },\\n },\\n },\\n },\\n parameters: [\\n {\\n name: 'access-token',\\n in: 'query',\\n description: 'Access token (/* access_token */)',\\n required: false,\\n schema: {\\n type: 'string',\\n },\\n },\\n ],\\n})",signature:"async createCustomer(@param({\\n name: 'access-token',\\n in: 'query',\\n description: 'Access token (/* access_token */)',\\n required: false,\\n schema: {\\n type: 'string',\\n },\\n}) accessToken: string | undefined, @requestBody({\\n description: 'Customer to add',\\n required: true,\\n content: {\\n 'application/json': {\\n schema: {\\n $ref: '#/components/schemas/Customer',\\n },\\n },\\n },\\n}) _requestBody: Customer): Promise",signatureForInterface:'createCustomer(accessToken: string | undefined, _requestBody: Customer): Promise',signatureForNamedParams:"createCustomer(params: { 'access-token': string; requestBody: Customer }): Promise",implementation:'return this.customerService.createCustomer(accessToken, _requestBody);'},{description:'Returns a customer based on a single ID',comments:['Returns a customer based on a single ID','','@param customerId ID of customer to fetch','@returns customer response'],decoration:"@operation('get', '/customers/{customer_id}', {\\n tags: [\\n 'Customer',\\n ],\\n description: 'Returns a customer based on a single ID',\\n 'x-implementation': \\"return {id: customerId, 'first-name': 'John', 'last-name': 'Smith'};\\",\\n operationId: 'find customer by id',\\n parameters: [\\n {\\n name: 'customer-id',\\n in: 'path',\\n description: 'ID of customer to fetch',\\n required: true,\\n schema: {\\n type: 'integer',\\n format: 'int64',\\n },\\n },\\n ],\\n responses: {\\n '200': {\\n description: 'customer response',\\n content: {\\n 'application/json': {\\n schema: {\\n $ref: '#/components/schemas/Customer',\\n },\\n },\\n },\\n },\\n },\\n})",signature:"async findCustomerById(@param({\\n name: 'customer-id',\\n in: 'path',\\n description: 'ID of customer to fetch',\\n required: true,\\n schema: {\\n type: 'integer',\\n format: 'int64',\\n },\\n}) customerId: number): Promise",signatureForInterface:'findCustomerById(customerId: number): Promise',signatureForNamedParams:'findCustomerById(params: { customer_id: number }): Promise',implementation:"return {id: customerId, 'first-name': 'John', 'last-name': 'Smith'};"}],methodMappingObject:"{\\n getCustomers: 'getCustomers',\\n createCustomer: 'createCustomer',\\n findCustomerById: 'find customer by id',\\n}"}] `; diff --git a/packages/cli/test/unit/openapi/spec-helper.unit.js b/packages/cli/test/unit/openapi/spec-helper.unit.js index ffffe8d1595c..9e07b0a3e475 100644 --- a/packages/cli/test/unit/openapi/spec-helper.unit.js +++ b/packages/cli/test/unit/openapi/spec-helper.unit.js @@ -1,6 +1,8 @@ const expect = require('@loopback/testlab').expect; -const getMethodName = - require('../../../generators/openapi/spec-helper').getMethodName; +const { + getMethodName, + generateControllerSpecs, +} = require('../../../generators/openapi/spec-helper'); describe('Spec Helpers', () => { describe('getMethodName', () => { @@ -45,4 +47,51 @@ describe('Spec Helpers', () => { ); }); }); + + describe('generateControllerSpecs', () => { + function implementationOf(operation) { + const apiSpec = { + openapi: '3.0.0', + info: {title: 'Pet API', version: '1.0.0'}, + paths: {'/pets': {post: {operationId: 'getPet', ...operation}}}, + }; + const [controller] = generateControllerSpecs(apiSpec, { + objectTypeMapping: new Map(), + schemaMapping: {}, + }); + return controller.methods[0].implementation; + } + + it('passes a hyphenated parameter by the name the method declares', () => { + const implementation = implementationOf({ + parameters: [ + { + name: 'pet-id', + in: 'query', + required: true, + schema: {type: 'string'}, + }, + ], + responses: {200: {description: 'ok'}}, + }); + + expect(implementation).to.equal( + 'return this.openApiService.getPet(petId);', + ); + }); + + it('passes the request body by the name the method declares', () => { + const implementation = implementationOf({ + parameters: [{name: 'limit', in: 'query', schema: {type: 'number'}}], + requestBody: { + content: {'application/json': {schema: {type: 'string'}}}, + }, + responses: {200: {description: 'ok'}}, + }); + + expect(implementation).to.equal( + 'return this.openApiService.getPet(limit, _requestBody);', + ); + }); + }); });