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 @@ -49,6 +49,7 @@ module.exports = class BelongsToRelationGenerator extends (
);

this.artifactInfo.relationPropertyName = options.relationName;
this.artifactInfo.keyTo = options.keyTo;
this.artifactInfo.targetModelPrimaryKey =
options.destinationModelPrimaryKey;
this.artifactInfo.targetModelPrimaryKeyType =
Expand Down Expand Up @@ -85,7 +86,11 @@ module.exports = class BelongsToRelationGenerator extends (
const relationName = options.relationName;
const defaultRelationName = options.defaultRelationName;
const foreignKeyName = options.foreignKeyName;
const fktype = options.destinationModelPrimaryKeyType;
const keyTo = options.keyTo;
const fktype = keyTo
? relationUtils.getModelPropertyType(modelDir, targetModel, keyTo) ||
options.destinationModelPrimaryKeyType
: options.destinationModelPrimaryKeyType;

const project = new relationUtils.AstLoopBackProject();
const sourceFile = relationUtils.addFileToProject(
Expand All @@ -103,6 +108,7 @@ module.exports = class BelongsToRelationGenerator extends (
defaultRelationName,
foreignKeyName,
fktype,
keyTo,
);

relationUtils.addProperty(sourceClass, modelProperty);
Expand All @@ -123,20 +129,29 @@ module.exports = class BelongsToRelationGenerator extends (
defaultRelationName,
foreignKeyName,
fktype,
keyTo,
) {
const keyToOption = keyTo ? `, keyTo: '${keyTo}'` : '';

// checks if relation name is customized
let relationDecorator = [
{
name: 'belongsTo',
arguments: [`() => ${className}`],
arguments: [
keyTo
? `() => ${className}, {keyTo: '${keyTo}'}`
: `() => ${className}`,
],
},
];
// already checked if the relation name is the same as the source key before
if (defaultRelationName !== relationName) {
relationDecorator = [
{
name: 'belongsTo',
arguments: [`() => ${className}, {name: '${relationName}'}`],
arguments: [
`() => ${className}, {name: '${relationName}'${keyToOption}}`,
],
},
];
}
Expand Down
4 changes: 4 additions & 0 deletions packages/cli/generators/relation/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,10 @@ module.exports = class RelationGenerator extends ArtifactGenerator {

debug('Invoke generator...');

if (this.options.keyTo) {
this.artifactInfo.keyTo = this.options.keyTo;
}

let relationGenerator;

this.artifactInfo.name = this.artifactInfo.relationType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class <%= controllerClassName %> {
@get('/<%= sourceModelPath %>/{id}/<%= targetModelName %>', {
responses: {
'200': {
description: '<%= targetModelClassName %> belonging to <%= sourceModelClassName %>',
description: '<%= targetModelClassName %> belonging to <%= sourceModelClassName %><%= keyTo ? " (resolved via " + targetModelClassName + "." + keyTo + ")" : "" %>',
content: {
'application/json': {
schema: getModelSchemaRef(<%= targetModelClassName %>),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,3 +373,147 @@ export class Employee extends Entity {
}

`;


exports[`lb4 relation generates belongsTo relation with keyTo option generated model includes keyTo in belongsTo decorator 1`] = `
import {Entity, model, property, belongsTo} from '@loopback/repository';
import {Customer} from './customer.model';

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

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

@belongsTo(() => Customer, {keyTo: 'name'})
customerId: string;

constructor(data?: Partial<Order>) {
super(data);
}
}

`;


exports[`lb4 relation generates belongsTo relation with keyTo option generated controller description includes resolved via reference 1`] = `
import {
repository,
} from '@loopback/repository';
import {
param,
get,
getModelSchemaRef,
} from '@loopback/rest';
import {
Order,
Customer,
} from '../models';
import {OrderRepository} from '../repositories';

export class OrderCustomerController {
constructor(
@repository(OrderRepository)
public orderRepository: OrderRepository,
) { }

@get('/orders/{id}/customer', {
responses: {
'200': {
description: 'Customer belonging to Order (resolved via Customer.name)',
content: {
'application/json': {
schema: getModelSchemaRef(Customer),
},
},
},
},
})
async getCustomer(
@param.path.number('id') id: typeof Order.prototype.id,
): Promise<Customer> {
return this.orderRepository.customer(id);
}
}

`;


exports[`lb4 relation generates belongsTo relation with keyTo and custom relation name generated model includes both name and keyTo in belongsTo decorator 1`] = `
import {Entity, model, property, belongsTo} from '@loopback/repository';
import {Customer} from './customer.model';

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

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

@belongsTo(() => Customer, {name: 'myCustomer', keyTo: 'name'})
customerId: string;

constructor(data?: Partial<Order>) {
super(data);
}
}

`;


exports[`lb4 relation generates belongsTo relation with keyTo and custom relation name generated controller description includes resolved via reference with custom relation name 1`] = `
import {
repository,
} from '@loopback/repository';
import {
param,
get,
getModelSchemaRef,
} from '@loopback/rest';
import {
Order,
Customer,
} from '../models';
import {OrderRepository} from '../repositories';

export class OrderCustomerController {
constructor(
@repository(OrderRepository)
public orderRepository: OrderRepository,
) { }

@get('/orders/{id}/customer', {
responses: {
'200': {
description: 'Customer belonging to Order (resolved via Customer.name)',
content: {
'application/json': {
schema: getModelSchemaRef(Customer),
},
},
},
},
})
async getCustomer(
@param.path.number('id') id: typeof Order.prototype.id,
): Promise<Customer> {
return this.orderRepository.myCustomer(id);
}
}

`;
Original file line number Diff line number Diff line change
Expand Up @@ -497,4 +497,81 @@ describe('lb4 relation', /** @this {Mocha.Suite} */ function () {
});
},
);

context('generates belongsTo relation with keyTo option', () => {
before(async function runGeneratorWithAnswers() {
await sandbox.reset();
await testUtils
.executeGenerator(generator)
.inDir(sandbox.path, () =>
testUtils.givenLBProject(sandbox.path, {
additionalFiles: SANDBOX_FILES,
}),
)
.withArguments([
'--config',
`{"relationType":"belongsTo","sourceModel":"Order","destinationModel":"Customer","foreignKeyName":"customerId","keyTo":"name"}`,
]);
});

it('generated model includes keyTo in belongsTo decorator', async () => {
const sourceFilePath = path.join(
sandbox.path,
MODEL_APP_PATH,
sourceFileName,
);
assert.file(sourceFilePath);
expectFileToMatchSnapshot(sourceFilePath);
});

it('generated controller description includes resolved via reference', async () => {
const filePath = path.join(
sandbox.path,
CONTROLLER_PATH,
controllerFileName,
);
assert.file(filePath);
expectFileToMatchSnapshot(filePath);
});
});

context(
'generates belongsTo relation with keyTo and custom relation name',
() => {
before(async function runGeneratorWithAnswers() {
await sandbox.reset();
await testUtils
.executeGenerator(generator)
.inDir(sandbox.path, () =>
testUtils.givenLBProject(sandbox.path, {
additionalFiles: SANDBOX_FILES,
}),
)
.withArguments([
'--config',
`{"relationType":"belongsTo","sourceModel":"Order","destinationModel":"Customer","foreignKeyName":"customerId","relationName":"myCustomer","keyTo":"name"}`,
]);
});

it('generated model includes both name and keyTo in belongsTo decorator', async () => {
const sourceFilePath = path.join(
sandbox.path,
MODEL_APP_PATH,
sourceFileName,
);
assert.file(sourceFilePath);
expectFileToMatchSnapshot(sourceFilePath);
});

it('generated controller description includes resolved via reference with custom relation name', async () => {
const filePath = path.join(
sandbox.path,
CONTROLLER_PATH,
controllerFileName,
);
assert.file(filePath);
expectFileToMatchSnapshot(filePath);
});
},
);
});
Loading