From f0b96de2a373cf62b6c676de40f623b909c786a1 Mon Sep 17 00:00:00 2001 From: Agnes Lin Date: Mon, 20 Jan 2020 13:43:04 -0500 Subject: [PATCH 1/2] refactor(cli): update openAPI CLI tests to snapshots --- .../openapi-petstore.integration.snapshots.js | 168 ++++++++++++++++++ ...to-with-anonymous.integration.snapshots.js | 151 ++++++++++++++++ .../openapi-uspto.integration.snapshots.js | 146 +++++++++++++++ .../openapi-petstore.integration.js | 40 ++--- ...penapi-uspto-with-anonymous.integration.js | 39 ++-- .../generators/openapi-uspto.integration.js | 38 ++-- 6 files changed, 505 insertions(+), 77 deletions(-) create mode 100644 packages/cli/snapshots/integration/generators/openapi-petstore.integration.snapshots.js create mode 100644 packages/cli/snapshots/integration/generators/openapi-uspto-with-anonymous.integration.snapshots.js create mode 100644 packages/cli/snapshots/integration/generators/openapi-uspto.integration.snapshots.js diff --git a/packages/cli/snapshots/integration/generators/openapi-petstore.integration.snapshots.js b/packages/cli/snapshots/integration/generators/openapi-petstore.integration.snapshots.js new file mode 100644 index 000000000000..cab168735d09 --- /dev/null +++ b/packages/cli/snapshots/integration/generators/openapi-petstore.integration.snapshots.js @@ -0,0 +1,168 @@ +// IMPORTANT +// This snapshot file is auto-generated, but designed for humans. +// It should be checked into source control and tracked carefully. +// Re-generate by setting UPDATE_SNAPSHOTS=1 and running tests. +// Make sure to inspect the changes in the snapshots below. +// Do not ignore changes! + +'use strict'; + +exports[`openapi-generator specific files generates all the proper files 1`] = ` +export * from './open-api.controller'; + +`; + + +exports[`openapi-generator specific files generates all the proper files 2`] = ` +/* eslint-disable @typescript-eslint/no-explicit-any */ +import {operation, param, requestBody} from '@loopback/rest'; +import {Pet} from '../models/pet.model'; +import {NewPet} from '../models/new-pet.model'; + +/** + * The controller class is generated from OpenAPI spec with operations tagged + * by + * + */ +export class OpenApiController { + constructor() {} + + /** + * Returns all pets from the system that the user has access to +Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia. + +Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien. + + * + + * @param tags tags to filter by + * @param limit maximum number of results to return + * @returns pet response + */ + @operation('get', '/pets') + async findPets(@param({name: 'tags', in: 'query'}) tags: string[], @param({name: 'limit', in: 'query'}) limit: number): Promise { + throw new Error('Not implemented'); + } + + /** + * Creates a new pet in the store. Duplicates are allowed + * + + * @param _requestBody Pet to add to the store + * @returns pet response + */ + @operation('post', '/pets') + async addPet(@requestBody() _requestBody: NewPet): Promise { + throw new Error('Not implemented'); + } + + /** + * Returns a user based on a single ID, if the user does not have access to the pet + * + + * @param id ID of pet to fetch + * @returns pet response + */ + @operation('get', '/pets/{id}') + async findPetById(@param({name: 'id', in: 'path'}) id: number): Promise { + throw new Error('Not implemented'); + } + + /** + * deletes a single pet based on the ID supplied + * + + * @param id ID of pet to delete + */ + @operation('delete', '/pets/{id}') + async deletePet(@param({name: 'id', in: 'path'}) id: number): Promise { + throw new Error('Not implemented'); + } + +} + + +`; + + +exports[`openapi-generator specific files generates all the proper files 3`] = ` +/* eslint-disable @typescript-eslint/no-explicit-any */ +import {NewPet} from './new-pet.model'; +/** + * The model type is generated from OpenAPI schema - Pet + * Pet + */ +export type Pet = NewPet & { + id: number; +}; + + +`; + + +exports[`openapi-generator specific files generates all the proper files 4`] = ` +/* eslint-disable @typescript-eslint/no-explicit-any */ +import {model, property} from '@loopback/repository'; + +/** + * The model class is generated from OpenAPI schema - NewPet + * NewPet + */ +@model({name: 'NewPet'}) +export class NewPet { + constructor(data?: Partial) { + if (data != null && typeof data === 'object') { + Object.assign(this, data); + } + } + + /** + * + */ + @property({required: true}) + name: string; + + /** + * + */ + @property() + tag?: string; + +} + + +`; + + +exports[`openapi-generator specific files generates all the proper files 5`] = ` +/* eslint-disable @typescript-eslint/no-explicit-any */ +import {model, property} from '@loopback/repository'; + +/** + * The model class is generated from OpenAPI schema - Error + * Error + */ +@model({name: 'Error'}) +export class Error { + constructor(data?: Partial) { + if (data != null && typeof data === 'object') { + Object.assign(this, data); + } + } + + /** + * + */ + @property({required: true}) + code: number; + + /** + * + */ + @property({required: true}) + message: string; + +} + + +`; diff --git a/packages/cli/snapshots/integration/generators/openapi-uspto-with-anonymous.integration.snapshots.js b/packages/cli/snapshots/integration/generators/openapi-uspto-with-anonymous.integration.snapshots.js new file mode 100644 index 000000000000..4b4f868605f2 --- /dev/null +++ b/packages/cli/snapshots/integration/generators/openapi-uspto-with-anonymous.integration.snapshots.js @@ -0,0 +1,151 @@ +// IMPORTANT +// This snapshot file is auto-generated, but designed for humans. +// It should be checked into source control and tracked carefully. +// Re-generate by setting UPDATE_SNAPSHOTS=1 and running tests. +// Make sure to inspect the changes in the snapshots below. +// Do not ignore changes! + +'use strict'; + +exports[`openapi-generator specific files generates all the proper files 1`] = ` +/* eslint-disable @typescript-eslint/no-explicit-any */ +import {operation, param, requestBody} from '@loopback/rest'; +import {PerformSearchRequestBody} from '../models/perform-search-request-body.model'; +import {PerformSearchResponseBody} from '../models/perform-search-response-body.model'; + +/** + * The controller class is generated from OpenAPI spec with operations tagged + * by search + * Search a data set + */ +export class SearchController { + constructor() {} + + /** + * This API is based on Solr/Lucense Search. The data is indexed using SOLR. This GET API returns the list of all the searchable field names that are in the Solr Index. Please see the 'fields' attribute which returns an array of field names. Each field or a combination of fields can be searched using the Solr/Lucene Syntax. Please refer https://lucene.apache.org/core/3_6_2/queryparsersyntax.html#Overview for the query syntax. List of field names that are searchable can be determined using above GET api. + * + + * @param _requestBody + * @param version Version of the dataset. + * @param dataset Name of the dataset. In this case, the default value is oa_citations + * @returns successful operation + */ + @operation('post', '/{dataset}/{version}/records') + async performSearch(@requestBody() _requestBody: PerformSearchRequestBody, @param({name: 'version', in: 'path'}) version: string, @param({name: 'dataset', in: 'path'}) dataset: string): Promise { + throw new Error('Not implemented'); + } + +} + + +`; + + +exports[`openapi-generator specific files generates all the proper files 2`] = ` +/* eslint-disable @typescript-eslint/no-explicit-any */ +import {operation, param, requestBody} from '@loopback/rest'; +import {DataSetList} from '../models/data-set-list.model'; + +/** + * The controller class is generated from OpenAPI spec with operations tagged + * by metadata + * Find out about the data sets + */ +export class MetadataController { + constructor() {} + + /** + * + * + + * @returns Returns a list of data sets + */ + @operation('get', '/') + async listDataSets(): Promise { + throw new Error('Not implemented'); + } + + /** + * This GET API returns the list of all the searchable field names that are in the oa_citations. Please see the 'fields' attribute which returns an array of field names. Each field or a combination of fields can be searched using the syntax options shown below. + * + + * @param dataset Name of the dataset. In this case, the default value is oa_citations + * @param version Version of the dataset. + * @returns The dataset api for the given version is found and it is accessible to consume. + */ + @operation('get', '/{dataset}/{version}/fields') + async listSearchableFields(@param({name: 'dataset', in: 'path'}) dataset: string, @param({name: 'version', in: 'path'}) version: string): Promise { + throw new Error('Not implemented'); + } + +} + + +`; + + +exports[`openapi-generator specific files generates all the proper files 3`] = ` +/* eslint-disable @typescript-eslint/no-explicit-any */ +import {model, property} from '@loopback/repository'; + +/** + * The model class is generated from OpenAPI schema - performSearchRequestBody + * performSearchRequestBody + */ +@model({name: 'performSearchRequestBody'}) +export class PerformSearchRequestBody { + constructor(data?: Partial) { + if (data != null && typeof data === 'object') { + Object.assign(this, data); + } + } + + /** + * Uses Lucene Query Syntax in the format of propertyName:value, propertyName:[num1 TO num2] and date range format: propertyName:[yyyyMMdd TO yyyyMMdd]. In the response please see the 'docs' element which has the list of record objects. Each record structure would consist of all the fields and their corresponding values. + */ + @property({required: true}) + criteria: string = '*:*'; + + /** + * Starting record number. Default value is 0. + */ + @property() + start?: number = 0; + + /** + * Specify number of rows to be returned. If you run the search with default values, in the response you will see 'numFound' attribute which will tell the number of records available in the dataset. + */ + @property() + rows?: number = 100; + +} + + +`; + + +exports[`openapi-generator specific files generates all the proper files 4`] = ` +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** + * The model type is generated from OpenAPI schema - { + [additionalProperty: string]: { + +}; +}[] + * performSearchResponseBody + */ +export type PerformSearchResponseBody = { + [additionalProperty: string]: { + +}; +}[]; + + +`; + + +exports[`openapi-generator specific files generates all the proper files 5`] = ` +export * from './metadata.controller'; +export * from './search.controller'; + +`; diff --git a/packages/cli/snapshots/integration/generators/openapi-uspto.integration.snapshots.js b/packages/cli/snapshots/integration/generators/openapi-uspto.integration.snapshots.js new file mode 100644 index 000000000000..75c356ce41d6 --- /dev/null +++ b/packages/cli/snapshots/integration/generators/openapi-uspto.integration.snapshots.js @@ -0,0 +1,146 @@ +// IMPORTANT +// This snapshot file is auto-generated, but designed for humans. +// It should be checked into source control and tracked carefully. +// Re-generate by setting UPDATE_SNAPSHOTS=1 and running tests. +// Make sure to inspect the changes in the snapshots below. +// Do not ignore changes! + +'use strict'; + +exports[`openapi-generator specific files generates all the proper files 1`] = ` +/* eslint-disable @typescript-eslint/no-explicit-any */ +import {operation, param, requestBody} from '@loopback/rest'; + +/** + * The controller class is generated from OpenAPI spec with operations tagged + * by search + * Search a data set + */ +export class SearchController { + constructor() {} + + /** + * This API is based on Solr/Lucense Search. The data is indexed using SOLR. This GET API returns the list of all the searchable field names that are in the Solr Index. Please see the 'fields' attribute which returns an array of field names. Each field or a combination of fields can be searched using the Solr/Lucene Syntax. Please refer https://lucene.apache.org/core/3_6_2/queryparsersyntax.html#Overview for the query syntax. List of field names that are searchable can be determined using above GET api. + * + + * @param _requestBody + * @param version Version of the dataset. + * @param dataset Name of the dataset. In this case, the default value is oa_citations + * @returns successful operation + */ + @operation('post', '/{dataset}/{version}/records') + async performSearch(@requestBody() _requestBody: { + criteria: string; + start?: number; + rows?: number; +}, @param({name: 'version', in: 'path'}) version: string, @param({name: 'dataset', in: 'path'}) dataset: string): Promise<{ + [additionalProperty: string]: { + +}; +}[]> { + throw new Error('Not implemented'); + } + +} + + +`; + + +exports[`openapi-generator specific files generates all the proper files 2`] = ` +/* eslint-disable @typescript-eslint/no-explicit-any */ +import {operation, param, requestBody} from '@loopback/rest'; +import {DataSetList} from '../models/data-set-list.model'; + +/** + * The controller class is generated from OpenAPI spec with operations tagged + * by metadata + * Find out about the data sets + */ +export class MetadataController { + constructor() {} + + /** + * + * + + * @returns Returns a list of data sets + */ + @operation('get', '/') + async listDataSets(): Promise { + throw new Error('Not implemented'); + } + + /** + * This GET API returns the list of all the searchable field names that are in the oa_citations. Please see the 'fields' attribute which returns an array of field names. Each field or a combination of fields can be searched using the syntax options shown below. + * + + * @param dataset Name of the dataset. In this case, the default value is oa_citations + * @param version Version of the dataset. + * @returns The dataset api for the given version is found and it is accessible to consume. + */ + @operation('get', '/{dataset}/{version}/fields') + async listSearchableFields(@param({name: 'dataset', in: 'path'}) dataset: string, @param({name: 'version', in: 'path'}) version: string): Promise { + throw new Error('Not implemented'); + } + +} + + +`; + + +exports[`openapi-generator specific files generates all the proper files 3`] = ` +export * from './metadata.controller'; +export * from './search.controller'; + +`; + + +exports[`openapi-generator specific files skips controllers not selected 1`] = ` +/* eslint-disable @typescript-eslint/no-explicit-any */ +import {operation, param, requestBody} from '@loopback/rest'; +import {DataSetList} from '../models/data-set-list.model'; + +/** + * The controller class is generated from OpenAPI spec with operations tagged + * by metadata + * Find out about the data sets + */ +export class MetadataController { + constructor() {} + + /** + * + * + + * @returns Returns a list of data sets + */ + @operation('get', '/') + async listDataSets(): Promise { + throw new Error('Not implemented'); + } + + /** + * This GET API returns the list of all the searchable field names that are in the oa_citations. Please see the 'fields' attribute which returns an array of field names. Each field or a combination of fields can be searched using the syntax options shown below. + * + + * @param dataset Name of the dataset. In this case, the default value is oa_citations + * @param version Version of the dataset. + * @returns The dataset api for the given version is found and it is accessible to consume. + */ + @operation('get', '/{dataset}/{version}/fields') + async listSearchableFields(@param({name: 'dataset', in: 'path'}) dataset: string, @param({name: 'version', in: 'path'}) version: string): Promise { + throw new Error('Not implemented'); + } + +} + + +`; + + +exports[`openapi-generator specific files skips controllers not selected 2`] = ` +export * from './metadata.controller'; + +`; diff --git a/packages/cli/test/integration/generators/openapi-petstore.integration.js b/packages/cli/test/integration/generators/openapi-petstore.integration.js index 2093a3f91e52..b13d2f37aa71 100644 --- a/packages/cli/test/integration/generators/openapi-petstore.integration.js +++ b/packages/cli/test/integration/generators/openapi-petstore.integration.js @@ -7,15 +7,15 @@ const path = require('path'); const assert = require('yeoman-assert'); +const {TestSandbox} = require('@loopback/testlab'); +const {expectFileToMatchSnapshot} = require('../../snapshots'); + const generator = path.join(__dirname, '../../../generators/openapi'); const specPath = path.join( __dirname, '../../fixtures/openapi/3.0/petstore-expanded.yaml', ); -const testlab = require('@loopback/testlab'); -const TestSandbox = testlab.TestSandbox; - // Test Sandbox const SANDBOX_PATH = path.resolve(__dirname, '../.sandbox'); const sandbox = new TestSandbox(SANDBOX_PATH); @@ -30,12 +30,11 @@ describe('openapi-generator specific files', function() { // eslint-disable-next-line no-invalid-this this.timeout(10000); - const index = path.resolve(SANDBOX_PATH, 'src/controllers/index.ts'); + const controIndex = path.resolve(SANDBOX_PATH, 'src/controllers/index.ts'); const controller = path.resolve( SANDBOX_PATH, 'src/controllers/open-api.controller.ts', ); - const petModel = path.resolve(SANDBOX_PATH, 'src/models/pet.model.ts'); const newPetModel = path.resolve(SANDBOX_PATH, 'src/models/new-pet.model.ts'); const errorModel = path.resolve(SANDBOX_PATH, 'src/models/error.model.ts'); @@ -49,33 +48,20 @@ describe('openapi-generator specific files', function() { .executeGenerator(generator) .inDir(SANDBOX_PATH, () => testUtils.givenLBProject(SANDBOX_PATH)) .withPrompts(props); - assert.file(controller); - assert.fileContent(controller, 'export class OpenApiController {'); - assert.fileContent(controller, `@operation('get', '/pets')`); - assert.fileContent( - controller, - `async findPets(@param({name: 'tags', in: 'query'}) tags: string[], ` + - `@param({name: 'limit', in: 'query'}) limit: number): Promise`, - ); + assert.file(controIndex); + expectFileToMatchSnapshot(controIndex); - assert.fileContent(index, `export * from './open-api.controller';`); + assert.file(controller); + expectFileToMatchSnapshot(controller); assert.file(petModel); - assert.fileContent(petModel, `import {NewPet} from './new-pet.model';`); - assert.fileContent( - petModel, - `export type Pet = NewPet & { - id: number; -};`, - ); + expectFileToMatchSnapshot(petModel); + assert.file(newPetModel); - assert.fileContent(newPetModel, `export class NewPet {`); - assert.fileContent(newPetModel, `@model({name: 'NewPet'})`); - assert.fileContent(newPetModel, `@property({required: true})`); - assert.fileContent(newPetModel, `name: string;`); - assert.fileContent(newPetModel, `@property()`); - assert.fileContent(newPetModel, `tag?: string`); + expectFileToMatchSnapshot(newPetModel); + assert.file(errorModel); + expectFileToMatchSnapshot(errorModel); }); }); diff --git a/packages/cli/test/integration/generators/openapi-uspto-with-anonymous.integration.js b/packages/cli/test/integration/generators/openapi-uspto-with-anonymous.integration.js index a175f8c254d8..e61306b6ffe3 100644 --- a/packages/cli/test/integration/generators/openapi-uspto-with-anonymous.integration.js +++ b/packages/cli/test/integration/generators/openapi-uspto-with-anonymous.integration.js @@ -7,12 +7,12 @@ const path = require('path'); const assert = require('yeoman-assert'); +const {TestSandbox} = require('@loopback/testlab'); +const {expectFileToMatchSnapshot} = require('../../snapshots'); + const generator = path.join(__dirname, '../../../generators/openapi'); const specPath = path.join(__dirname, '../../fixtures/openapi/3.0/uspto.yaml'); -const testlab = require('@loopback/testlab'); -const TestSandbox = testlab.TestSandbox; - // Test Sandbox const SANDBOX_PATH = path.resolve(__dirname, '../.sandbox'); const sandbox = new TestSandbox(SANDBOX_PATH); @@ -51,32 +51,19 @@ describe('openapi-generator specific files', () => { .inDir(SANDBOX_PATH, () => testUtils.givenLBProject(SANDBOX_PATH)) .withArguments('--promote-anonymous-schemas') .withPrompts(props); - assert.file(metadataController); + assert.file(searchController); + expectFileToMatchSnapshot(searchController); - assert.fileContent( - searchController, - `async performSearch(@requestBody() _requestBody: PerformSearchRequestBody, ` + - `@param({name: 'version', in: 'path'}) version: string, ` + - `@param({name: 'dataset', in: 'path'}) dataset: string): ` + - `Promise {`, - ); - - assert.fileContent( - performSearchRequestBodyModel, - 'export class PerformSearchRequestBody {', - ); + assert.file(metadataController); + expectFileToMatchSnapshot(metadataController); - assert.fileContent( - performSearchResponseBodyModel, - 'export type PerformSearchResponseBody = {', - ); + assert.file(performSearchRequestBodyModel); + expectFileToMatchSnapshot(performSearchRequestBodyModel); - assert.fileContent( - performSearchResponseBodyModel, - '[additionalProperty: string]: {', - ); + assert.file(performSearchResponseBodyModel); + expectFileToMatchSnapshot(performSearchResponseBodyModel); - assert.fileContent(index, `export * from './search.controller';`); - assert.fileContent(index, `export * from './metadata.controller';`); + assert.file(index); + expectFileToMatchSnapshot(index); }); }); diff --git a/packages/cli/test/integration/generators/openapi-uspto.integration.js b/packages/cli/test/integration/generators/openapi-uspto.integration.js index 54f46822ef02..dae564ca174d 100644 --- a/packages/cli/test/integration/generators/openapi-uspto.integration.js +++ b/packages/cli/test/integration/generators/openapi-uspto.integration.js @@ -7,12 +7,12 @@ const path = require('path'); const assert = require('yeoman-assert'); +const {TestSandbox} = require('@loopback/testlab'); +const {expectFileToMatchSnapshot} = require('../../snapshots'); + const generator = path.join(__dirname, '../../../generators/openapi'); const specPath = path.join(__dirname, '../../fixtures/openapi/3.0/uspto.yaml'); -const testlab = require('@loopback/testlab'); -const TestSandbox = testlab.TestSandbox; - // Test Sandbox const SANDBOX_PATH = path.resolve(__dirname, '../.sandbox'); const sandbox = new TestSandbox(SANDBOX_PATH); @@ -32,7 +32,7 @@ describe('openapi-generator specific files', () => { SANDBOX_PATH, 'src/controllers/metadata.controller.ts', ); - after('reset sandbox', async () => { + before('reset sandbox', async () => { await sandbox.reset(); }); @@ -42,26 +42,13 @@ describe('openapi-generator specific files', () => { .inDir(SANDBOX_PATH, () => testUtils.givenLBProject(SANDBOX_PATH)) .withPrompts(props); assert.file(searchController); + expectFileToMatchSnapshot(searchController); - assert.fileContent(metadataController, 'export class MetadataController {'); - assert.fileContent(metadataController, `@operation('get', '/')`); - assert.fileContent( - metadataController, - 'async listDataSets(): Promise {', - ); - assert.fileContent( - metadataController, - `@operation('get', '/{dataset}/{version}/fields')`, - ); - assert.fileContent( - metadataController, - `async listSearchableFields(@param({name: 'dataset', in: 'path'}) ` + - `dataset: string, @param({name: 'version', in: 'path'}) ` + - `version: string): Promise {`, - ); + assert.file(metadataController); + expectFileToMatchSnapshot(metadataController); - assert.fileContent(index, `export * from './search.controller';`); - assert.fileContent(index, `export * from './metadata.controller';`); + assert.file(index); + expectFileToMatchSnapshot(index); }); it('skips controllers not selected', async () => { @@ -73,8 +60,11 @@ describe('openapi-generator specific files', () => { controllerSelections: ['MetadataController'], }); assert.file(metadataController); + expectFileToMatchSnapshot(metadataController); + assert.noFile(searchController); - assert.noFileContent(index, `export * from './search.controller';`); - assert.fileContent(index, `export * from './metadata.controller';`); + + assert.file(index); + expectFileToMatchSnapshot(index); }); }); From 0f78684d473cc98c152aeac64fc6fb633e55835f Mon Sep 17 00:00:00 2001 From: Agnes Lin Date: Mon, 20 Jan 2020 14:56:07 -0500 Subject: [PATCH 2/2] fix(cli): index file should be updated. Add relation interface to model template --- packages/cli/generators/openapi/index.js | 32 ++++++++++++++----- .../src/models/model-template.ts.ejs | 7 ++++ .../openapi-petstore.integration.snapshots.js | 30 ++++++++++++++--- ...to-with-anonymous.integration.snapshots.js | 15 +++++++++ .../openapi-uspto.integration.snapshots.js | 12 +++++++ .../openapi-petstore.integration.js | 4 +++ ...penapi-uspto-with-anonymous.integration.js | 10 ++++-- .../generators/openapi-uspto.integration.js | 19 +++++++---- 8 files changed, 108 insertions(+), 21 deletions(-) diff --git a/packages/cli/generators/openapi/index.js b/packages/cli/generators/openapi/index.js index 9c7a1fc08dfa..1f5493cb39a2 100644 --- a/packages/cli/generators/openapi/index.js +++ b/packages/cli/generators/openapi/index.js @@ -12,6 +12,8 @@ const {validateUrlOrFile, escapeComment} = require('./utils'); const {getControllerFileName} = require('./spec-helper'); const updateIndex = require('../../lib/update-index'); +const MODEL = 'models'; +const CONTROLLER = 'controllers'; module.exports = class OpenApiGenerator extends BaseGenerator { // Note: arguments and options should be defined in the constructor. @@ -122,8 +124,9 @@ module.exports = class OpenApiGenerator extends BaseGenerator { async scaffold() { if (this.shouldExit()) return false; this._generateModels(); + await this._updateIndex(MODEL); this._generateControllers(); - await this._updateIndex(); + await this._updateIndex(CONTROLLER); } _generateControllers() { @@ -161,13 +164,26 @@ module.exports = class OpenApiGenerator extends BaseGenerator { } } - async _updateIndex() { - const targetDir = this.destinationPath(`src/controllers`); - for (const c of this.selectedControllers) { - // Check all files being generated to ensure they succeeded - const status = this.conflicter.generationStatus[c.fileName]; - if (status !== 'skip' && status !== 'identical') { - await updateIndex(targetDir, c.fileName); + // update index file for models and controllers + async _updateIndex(dir) { + if (dir === MODEL) { + const targetDir = this.destinationPath(`src/${MODEL}`); + for (const m of this.modelSpecs) { + // Check all files being generated to ensure they succeeded + const status = this.conflicter.generationStatus[m.fileName]; + if (status !== 'skip' && status !== 'identical') { + await updateIndex(targetDir, m.fileName); + } + } + } + if (dir === CONTROLLER) { + const targetDir = this.destinationPath(`src/${CONTROLLER}`); + for (const c of this.selectedControllers) { + // Check all files being generated to ensure they succeeded + const status = this.conflicter.generationStatus[c.fileName]; + if (status !== 'skip' && status !== 'identical') { + await updateIndex(targetDir, c.fileName); + } } } } diff --git a/packages/cli/generators/openapi/templates/src/models/model-template.ts.ejs b/packages/cli/generators/openapi/templates/src/models/model-template.ts.ejs index f738c8507ce1..ac4e02ac2517 100644 --- a/packages/cli/generators/openapi/templates/src/models/model-template.ts.ejs +++ b/packages/cli/generators/openapi/templates/src/models/model-template.ts.ejs @@ -40,3 +40,10 @@ export class <%- className %> { <%_ } -%> } +export interface <%= className %>Relations { + // describe navigational properties here +} + +export type <%= className %>WithRelations = <%= className %> & <%= className %>Relations; + + diff --git a/packages/cli/snapshots/integration/generators/openapi-petstore.integration.snapshots.js b/packages/cli/snapshots/integration/generators/openapi-petstore.integration.snapshots.js index cab168735d09..f29b6fba2475 100644 --- a/packages/cli/snapshots/integration/generators/openapi-petstore.integration.snapshots.js +++ b/packages/cli/snapshots/integration/generators/openapi-petstore.integration.snapshots.js @@ -8,12 +8,20 @@ 'use strict'; exports[`openapi-generator specific files generates all the proper files 1`] = ` -export * from './open-api.controller'; +export * from './pet.model'; +export * from './new-pet.model'; +export * from './error.model'; `; exports[`openapi-generator specific files generates all the proper files 2`] = ` +export * from './open-api.controller'; + +`; + + +exports[`openapi-generator specific files generates all the proper files 3`] = ` /* eslint-disable @typescript-eslint/no-explicit-any */ import {operation, param, requestBody} from '@loopback/rest'; import {Pet} from '../models/pet.model'; @@ -85,7 +93,7 @@ Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condime `; -exports[`openapi-generator specific files generates all the proper files 3`] = ` +exports[`openapi-generator specific files generates all the proper files 4`] = ` /* eslint-disable @typescript-eslint/no-explicit-any */ import {NewPet} from './new-pet.model'; /** @@ -100,7 +108,7 @@ export type Pet = NewPet & { `; -exports[`openapi-generator specific files generates all the proper files 4`] = ` +exports[`openapi-generator specific files generates all the proper files 5`] = ` /* eslint-disable @typescript-eslint/no-explicit-any */ import {model, property} from '@loopback/repository'; @@ -130,11 +138,18 @@ export class NewPet { } +export interface NewPetRelations { + // describe navigational properties here +} + +export type NewPetWithRelations = NewPet & NewPetRelations; + + `; -exports[`openapi-generator specific files generates all the proper files 5`] = ` +exports[`openapi-generator specific files generates all the proper files 6`] = ` /* eslint-disable @typescript-eslint/no-explicit-any */ import {model, property} from '@loopback/repository'; @@ -164,5 +179,12 @@ export class Error { } +export interface ErrorRelations { + // describe navigational properties here +} + +export type ErrorWithRelations = Error & ErrorRelations; + + `; diff --git a/packages/cli/snapshots/integration/generators/openapi-uspto-with-anonymous.integration.snapshots.js b/packages/cli/snapshots/integration/generators/openapi-uspto-with-anonymous.integration.snapshots.js index 4b4f868605f2..f9b32ba0a021 100644 --- a/packages/cli/snapshots/integration/generators/openapi-uspto-with-anonymous.integration.snapshots.js +++ b/packages/cli/snapshots/integration/generators/openapi-uspto-with-anonymous.integration.snapshots.js @@ -120,6 +120,13 @@ export class PerformSearchRequestBody { } +export interface PerformSearchRequestBodyRelations { + // describe navigational properties here +} + +export type PerformSearchRequestBodyWithRelations = PerformSearchRequestBody & PerformSearchRequestBodyRelations; + + `; @@ -145,6 +152,14 @@ export type PerformSearchResponseBody = { exports[`openapi-generator specific files generates all the proper files 5`] = ` +export * from './data-set-list.model'; +export * from './perform-search-request-body.model'; +export * from './perform-search-response-body.model'; + +`; + + +exports[`openapi-generator specific files generates all the proper files 6`] = ` export * from './metadata.controller'; export * from './search.controller'; diff --git a/packages/cli/snapshots/integration/generators/openapi-uspto.integration.snapshots.js b/packages/cli/snapshots/integration/generators/openapi-uspto.integration.snapshots.js index 75c356ce41d6..5aafcdafada4 100644 --- a/packages/cli/snapshots/integration/generators/openapi-uspto.integration.snapshots.js +++ b/packages/cli/snapshots/integration/generators/openapi-uspto.integration.snapshots.js @@ -91,6 +91,12 @@ export class MetadataController { exports[`openapi-generator specific files generates all the proper files 3`] = ` +export * from './data-set-list.model'; + +`; + + +exports[`openapi-generator specific files generates all the proper files 4`] = ` export * from './metadata.controller'; export * from './search.controller'; @@ -141,6 +147,12 @@ export class MetadataController { exports[`openapi-generator specific files skips controllers not selected 2`] = ` +export * from './data-set-list.model'; + +`; + + +exports[`openapi-generator specific files skips controllers not selected 3`] = ` export * from './metadata.controller'; `; diff --git a/packages/cli/test/integration/generators/openapi-petstore.integration.js b/packages/cli/test/integration/generators/openapi-petstore.integration.js index b13d2f37aa71..2ce78aea2e72 100644 --- a/packages/cli/test/integration/generators/openapi-petstore.integration.js +++ b/packages/cli/test/integration/generators/openapi-petstore.integration.js @@ -30,6 +30,7 @@ describe('openapi-generator specific files', function() { // eslint-disable-next-line no-invalid-this this.timeout(10000); + const modelIndex = path.resolve(SANDBOX_PATH, 'src/models/index.ts'); const controIndex = path.resolve(SANDBOX_PATH, 'src/controllers/index.ts'); const controller = path.resolve( SANDBOX_PATH, @@ -49,6 +50,9 @@ describe('openapi-generator specific files', function() { .inDir(SANDBOX_PATH, () => testUtils.givenLBProject(SANDBOX_PATH)) .withPrompts(props); + assert.file(modelIndex); + expectFileToMatchSnapshot(modelIndex); + assert.file(controIndex); expectFileToMatchSnapshot(controIndex); diff --git a/packages/cli/test/integration/generators/openapi-uspto-with-anonymous.integration.js b/packages/cli/test/integration/generators/openapi-uspto-with-anonymous.integration.js index e61306b6ffe3..529adced7eeb 100644 --- a/packages/cli/test/integration/generators/openapi-uspto-with-anonymous.integration.js +++ b/packages/cli/test/integration/generators/openapi-uspto-with-anonymous.integration.js @@ -23,7 +23,8 @@ const props = { }; describe('openapi-generator specific files', () => { - const index = path.resolve(SANDBOX_PATH, 'src/controllers/index.ts'); + const modelIndex = path.resolve(SANDBOX_PATH, 'src/models/index.ts'); + const controIndex = path.resolve(SANDBOX_PATH, 'src/controllers/index.ts'); const searchController = path.resolve( SANDBOX_PATH, 'src/controllers/search.controller.ts', @@ -63,7 +64,10 @@ describe('openapi-generator specific files', () => { assert.file(performSearchResponseBodyModel); expectFileToMatchSnapshot(performSearchResponseBodyModel); - assert.file(index); - expectFileToMatchSnapshot(index); + assert.file(modelIndex); + expectFileToMatchSnapshot(modelIndex); + + assert.file(controIndex); + expectFileToMatchSnapshot(controIndex); }); }); diff --git a/packages/cli/test/integration/generators/openapi-uspto.integration.js b/packages/cli/test/integration/generators/openapi-uspto.integration.js index dae564ca174d..ae506c7a948f 100644 --- a/packages/cli/test/integration/generators/openapi-uspto.integration.js +++ b/packages/cli/test/integration/generators/openapi-uspto.integration.js @@ -23,7 +23,8 @@ const props = { }; describe('openapi-generator specific files', () => { - const index = path.resolve(SANDBOX_PATH, 'src/controllers/index.ts'); + const modelIndex = path.resolve(SANDBOX_PATH, 'src/models/index.ts'); + const controIndex = path.resolve(SANDBOX_PATH, 'src/controllers/index.ts'); const searchController = path.resolve( SANDBOX_PATH, 'src/controllers/search.controller.ts', @@ -32,7 +33,7 @@ describe('openapi-generator specific files', () => { SANDBOX_PATH, 'src/controllers/metadata.controller.ts', ); - before('reset sandbox', async () => { + after('reset sandbox', async () => { await sandbox.reset(); }); @@ -47,8 +48,11 @@ describe('openapi-generator specific files', () => { assert.file(metadataController); expectFileToMatchSnapshot(metadataController); - assert.file(index); - expectFileToMatchSnapshot(index); + assert.file(modelIndex); + expectFileToMatchSnapshot(modelIndex); + + assert.file(controIndex); + expectFileToMatchSnapshot(controIndex); }); it('skips controllers not selected', async () => { @@ -64,7 +68,10 @@ describe('openapi-generator specific files', () => { assert.noFile(searchController); - assert.file(index); - expectFileToMatchSnapshot(index); + assert.file(modelIndex); + expectFileToMatchSnapshot(modelIndex); + + assert.file(controIndex); + expectFileToMatchSnapshot(controIndex); }); });