Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,57 @@ module.exports = class BelongsToRelationGenerator extends (
path.join(this.artifactInfo.outDir, this.artifactInfo.outFile),
);

this.copyTemplatedFiles(source, dest, this.artifactInfo);
await relationUtils.addExportController(
this,
path.resolve(this.artifactInfo.outDir, 'index.ts'),
this.artifactInfo.controllerClassName,
utils.toFileName(this.artifactInfo.name) + '.controller',
);
if (this.fs.exists(dest)) {
const project = new relationUtils.AstLoopBackProject();
const sourceFile = project.addSourceFileAtPath(dest);
const sourceClass = relationUtils.getClassObj(
sourceFile,
this.artifactInfo.controllerClassName,
);
const structure = sourceClass.getStructure();
structure.methods.forEach((method, index) => {
if (method.name.startsWith('get')) {
const {statements, parameters} = method;
const lastStatementIndex = statements.length - 1;
let returnStatement = statements[lastStatementIndex];
returnStatement = returnStatement.substring(
returnStatement.indexOf('return') + 6,
returnStatement.lastIndexOf(';'),
);
returnStatement = returnStatement.trim();

if (returnStatement.startsWith('[')) {
returnStatement = returnStatement.substring(
returnStatement.indexOf('[') + 1,
returnStatement.lastIndexOf(']'),
);
}
returnStatement = `${returnStatement},\n\t this.${this.artifactInfo.paramSourceRepository}.${this.artifactInfo.relationPropertyName}(${this.artifactInfo.sourceModelPrimaryKey})`;
structure.methods[index].statements[lastStatementIndex] =
`return [${returnStatement}];`;
structure.methods[index].returnType =
`Promise<Promise<${this.artifactInfo.targetModelClassName}>[]>`;
parameters.forEach(({decorators}, paramIndex) => {
decorators.forEach((decorator, decorIndex) => {
structure.methods[index].parameters[paramIndex].decorators[
decorIndex
].name = `param.path.${decorator.name}`;
});
});
}
});
sourceClass.set(structure);
sourceClass.formatText();
await sourceFile.save();
} else {
this.copyTemplatedFiles(source, dest, this.artifactInfo);
await relationUtils.addExportController(
this,
path.resolve(this.artifactInfo.outDir, 'index.ts'),
this.artifactInfo.controllerClassName,
utils.toFileName(this.artifactInfo.name) + '.controller',
);
}
}

async generateModels(options) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,92 @@ export * from './order-customer.controller';
`;


exports[`lb4 relation checks if the controller file created for multiple relations answers {"relationType":"belongsTo","sourceModel":"Task","destinationModel":"Employee","relationName":"assignedTo"} checks controller content with belongsTo relation for multiple relations 1`] = `
import {
repository,
} from '@loopback/repository';
import {
param,
get,
getModelSchemaRef,
} from '@loopback/rest';
import {
Task,
Employee,
} from '../models';
import {TaskRepository} from '../repositories';

export class TaskEmployeeController {
constructor(
@repository(TaskRepository)
public taskRepository: TaskRepository,
) { }

@get('/tasks/{id}/employee', {
responses: {
'200': {
description: 'Employee belonging to Task',
content: {
'application/json': {
schema: getModelSchemaRef(Employee),
},
},
},
},
})
async getEmployee(
@param.path.number('id') id: typeof Task.prototype.id,
): Promise<Employee> {
return this.taskRepository.assignedTo(id);
}
}

`;


exports[`lb4 relation checks if the controller file created for multiple relations answers {"relationType":"belongsTo","sourceModel":"Task","destinationModel":"Employee","relationName":"createdBy"} checks controller content with belongsTo relation for multiple relations 1`] = `
import {
repository,
} from '@loopback/repository';
import {
param,
get,
getModelSchemaRef,
} from '@loopback/rest';
import {
Task,
Employee,
} from '../models';
import {TaskRepository} from '../repositories';

export class TaskEmployeeController {
constructor(
@repository(TaskRepository)
public taskRepository: TaskRepository,
) { }

@get('/tasks/{id}/employee', {
responses: {
'200': {
description: 'Employee belonging to Task',
content: {
'application/json': {
schema: getModelSchemaRef(Employee),
},
},
},
},
})
async getEmployee(
@param.path.number('id') id: typeof Task.prototype.id,
): Promise<Employee> {
return this.taskRepository.createdBy(id);
}
}

`;


exports[`lb4 relation checks if the controller file created for same table relation answers {"relationType":"belongsTo","sourceModel":"Employee","destinationModel":"Employee"} checks controller content with belongsTo relation with same table 1`] = `
export class EmployeeController {}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class TaskEmployeeController {}
1 change: 1 addition & 0 deletions packages/cli/test/fixtures/relation/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ exports.SANDBOX_FILES = [
SourceEntries.PatientRepository,
SourceEntries.AppointmentRepository,
SourceEntries.EmployeeRepository,
SourceEntries.TaskRepository,

SourceEntries.AccountModel,
SourceEntries.CustomerModel,
Expand Down
20 changes: 20 additions & 0 deletions packages/cli/test/fixtures/relation/models/task.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {Entity, model, property} from '@loopback/repository';

@model()
export class Task extends Entity {
@property({
type: 'number',
id: true,
default: 0,
})
id?: number;

@property({
type: 'string',
})
title?: string;

constructor(data?: Partial<Task>) {
super(data);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import {inject} from '@loopback/core';
import {BelongsToAccessor, DefaultCrudRepository} from '@loopback/repository';
import {DbDataSource} from '../datasources';
import {Customer, Task} from '../models';

export class TaskRepository extends DefaultCrudRepository<
Task,
typeof Task.prototype.id
> {
public readonly myCustomer: BelongsToAccessor<
Customer,
typeof Task.prototype.id
>;
constructor(@inject('datasources.db') dataSource: DbDataSource) {
super(Task, dataSource);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const sandbox = new TestSandbox(path.resolve(__dirname, '../.sandbox'));
const sourceFileName = 'order.model.ts';
const controllerFileName = 'order-customer.controller.ts';
const controllerFileNameForSameTableRelation = 'employee.controller.ts';
const controllerFileNameForMultipleRelations = 'task-employee.controller.ts';
const repositoryFileName = 'order.repository.ts';
const repositoryFileNameForSameTableRelation = 'employee.repository.ts';
// speed up tests by avoiding reading docs
Expand Down Expand Up @@ -497,4 +498,52 @@ describe('lb4 relation', /** @this {Mocha.Suite} */ function () {
});
},
);

context(
'checks if the controller file created for multiple relations',
() => {
const promptArray = [
{
relationType: 'belongsTo',
sourceModel: 'Task',
destinationModel: 'Employee',
relationName: 'createdBy',
},
{
relationType: 'belongsTo',
sourceModel: 'Task',
destinationModel: 'Employee',
relationName: 'assignedTo',
},
];
promptArray.forEach(function (multiItemPrompt) {
describe('answers ' + JSON.stringify(multiItemPrompt), () => {
suite(multiItemPrompt);
});
});
function suite(multiItemPrompt) {
before(async function runGeneratorWithAnswers() {
await sandbox.reset();
await testUtils
.executeGenerator(generator)
.inDir(sandbox.path, () =>
testUtils.givenLBProject(sandbox.path, {
additionalFiles: SANDBOX_FILES,
}),
)
.withOptions(options)
.withPrompts(multiItemPrompt);
});
it('checks controller content with belongsTo relation for multiple relations', async () => {
const filePath = path.join(
sandbox.path,
CONTROLLER_PATH,
controllerFileNameForMultipleRelations,
);
assert.file(filePath);
expectFileToMatchSnapshot(filePath);
});
}
},
);
});
Loading