Skip to content

Commit

Permalink
Merge pull request nestjsx#353 from nestjsx/fix/typeorm-create-one-re…
Browse files Browse the repository at this point in the history
…load

feat(crud,typeorm): added returnShallow option to createOneBase
  • Loading branch information
michaelyali authored Dec 18, 2019
2 parents ee2ba45 + 4df0f66 commit 1517b90
Show file tree
Hide file tree
Showing 7 changed files with 82 additions and 10 deletions.
23 changes: 17 additions & 6 deletions packages/crud-typeorm/src/typeorm-crud.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,14 +98,29 @@ export class TypeOrmCrudService<T> extends CrudService<T> {
* @param dto
*/
public async createOne(req: CrudRequest, dto: DeepPartial<T>): Promise<T> {
const { returnShallow } = req.options.routes.createOneBase;
const entity = this.prepareEntityBeforeSave(dto, req.parsed);

/* istanbul ignore if */
if (!entity) {
this.throwBadRequestException(`Empty data. Nothing to save.`);
}

return this.repo.save<any>(entity);
const saved = await this.repo.save<any>(entity);

if (returnShallow) {
return saved;
} else {
const primaryParam = this.getPrimaryParam(req.options);

/* istanbul ignore if */
if (!primaryParam && /* istanbul ignore next */ isNil(saved[primaryParam])) {
return saved;
} else {
req.parsed.search = { [primaryParam]: saved[primaryParam] };
return this.getOneOrFail(req);
}
}
}

/**
Expand Down Expand Up @@ -181,7 +196,7 @@ export class TypeOrmCrudService<T> extends CrudService<T> {
if (returnShallow) {
return replaced;
} else {
const primaryParam = this.getPrimaryParam(req.options.params);
const primaryParam = this.getPrimaryParam(req.options);

/* istanbul ignore if */
if (!primaryParam) {
Expand Down Expand Up @@ -932,8 +947,4 @@ export class TypeOrmCrudService<T> extends CrudService<T> {
this.throwBadRequestException(`Invalid column '${cond.field}' value`);
}
}

private getPrimaryParam(params: any): string {
return objKeys(params).find((param) => params[param] && params[param].primary);
}
}
12 changes: 12 additions & 0 deletions packages/crud-typeorm/test/__fixture__/devices.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';

import { TypeOrmCrudService } from '../../../crud-typeorm/src/typeorm-crud.service';
import { Device } from '../../../../integration/crud-typeorm/devices';

@Injectable()
export class DevicesService extends TypeOrmCrudService<Device> {
constructor(@InjectRepository(Device) repo) {
super(repo);
}
}
38 changes: 37 additions & 1 deletion packages/crud-typeorm/test/c.basic-crud.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import { Crud } from '@nestjsx/crud';
import { RequestQueryBuilder } from '@nestjsx/crud-request';
import * as request from 'supertest';
import { Company } from '../../../integration/crud-typeorm/companies';
import { Device } from '../../../integration/crud-typeorm/devices';
import { withCache } from '../../../integration/crud-typeorm/orm.config';
import { Project } from '../../../integration/crud-typeorm/projects';
import { User } from '../../../integration/crud-typeorm/users';
import { UserProfile } from '../../../integration/crud-typeorm/users-profiles';
import { HttpExceptionFilter } from '../../../integration/shared/https-exception.filter';
import { CompaniesService } from './__fixture__/companies.service';
import { UsersService } from './__fixture__/users.service';
import { DevicesService } from './__fixture__/devices.service';

// tslint:disable:max-classes-per-file no-shadowed-variable
describe('#crud-typeorm', () => {
Expand Down Expand Up @@ -233,22 +235,44 @@ describe('#crud-typeorm', () => {
constructor(public service: UsersService) {}
}

@Crud({
model: { type: Device },
params: {
deviceKey: {
field: 'deviceKey',
type: 'uuid',
primary: true,
},
},
routes: {
createOneBase: {
returnShallow: true,
},
},
})
@Controller('devices')
class DevicesController {
constructor(public service: DevicesService) {}
}

beforeAll(async () => {
const fixture = await Test.createTestingModule({
imports: [
TypeOrmModule.forRoot({ ...withCache, logging: false }),
TypeOrmModule.forFeature([Company, Project, User, UserProfile]),
TypeOrmModule.forFeature([Company, Project, User, UserProfile, Device]),
],
controllers: [
CompaniesController,
UsersController,
UsersController2,
UsersController3,
DevicesController,
],
providers: [
{ provide: APP_FILTER, useClass: HttpExceptionFilter },
CompaniesService,
UsersService,
DevicesService,
],
}).compile();

Expand Down Expand Up @@ -441,6 +465,18 @@ describe('#crud-typeorm', () => {
done();
});
});
it('should return with `returnShallow`', (done) => {
const dto: any = { description: 'returnShallow is true' };
return request(server)
.post('/devices')
.send(dto)
.end((_, res) => {
expect(res.status).toBe(201);
expect(res.body.deviceKey).toBeTruthy();
expect(res.body.description).toBeTruthy();
done();
});
});
});

describe('#createManyBase', () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/crud/src/interfaces/routes-options.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ export interface GetMayRouteOptions extends BaseRouteOptions {}

export interface GetOneRouteOptions extends BaseRouteOptions {}

export interface CreateOneRouteOptions extends BaseRouteOptions {}
export interface CreateOneRouteOptions extends BaseRouteOptions {
returnShallow?: boolean;
}

export interface CreateManyRouteOptions extends BaseRouteOptions {}

Expand Down
2 changes: 1 addition & 1 deletion packages/crud/src/module/crud-config.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class CrudConfigService {
routes: {
getManyBase: { interceptors: [], decorators: [] },
getOneBase: { interceptors: [], decorators: [] },
createOneBase: { interceptors: [], decorators: [] },
createOneBase: { interceptors: [], decorators: [], returnShallow: false },
createManyBase: { interceptors: [], decorators: [] },
updateOneBase: {
interceptors: [],
Expand Down
11 changes: 11 additions & 0 deletions packages/crud/src/services/crud-service.abstract.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { ParsedRequestParams } from '@nestjsx/crud-request';
import { objKeys } from '@nestjsx/util';

import {
CreateManyDto,
Expand Down Expand Up @@ -110,4 +111,14 @@ export abstract class CrudService<T> {
? query.offset
: null;
}

/**
* Get primary param name from CrudOptions
* @param options
*/
getPrimaryParam(options: CrudRequestOptions): string {
return objKeys(options.params).find(
(param) => options.params[param] && options.params[param].primary,
);
}
}
2 changes: 1 addition & 1 deletion packages/crud/test/crud-config.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ describe('#crud', () => {
decorators: [],
},
getOneBase: { interceptors: [], decorators: [] },
createOneBase: { interceptors: [], decorators: [] },
createOneBase: { interceptors: [], decorators: [], returnShallow: false },
createManyBase: { interceptors: [], decorators: [] },
updateOneBase: {
interceptors: [],
Expand Down

0 comments on commit 1517b90

Please sign in to comment.