Giter Site home page Giter Site logo

typeorm-routing-controllers-extensions's Introduction

routing-controllers integration with TypeORM

This extension for TypeORM provides handy decorators that can be used with routing-controllers.

Installation

  • Install module:

npm install typeorm-routing-controllers-extensions --save

  • Install routing-controllers:

npm install routing-controllers --save

  • That's all, start using decorators!

Usage

All decorators can be used on properties and constructor arguments, e.g. you can use both property and constructor injection.

@EntityFromParam

Creates entity from the request parameter.

Example:

import {JsonController, Get} from "routing-controllers";
import {EntityFromParam} from "typeorm-routing-controllers-extensions";
import {User} from "../entity/User";

@JsonController()
export class UserController {

    @Get("/users/:id")
    get(@EntityFromParam("id") user: User) {
        return user;
    }

}

@EntityFromQuery

Creates entity from the request query parameter.

Example:

import {JsonController, Get} from "routing-controllers";
import {EntityFromQuery} from "typeorm-routing-controllers-extensions";
import {User} from "../entity/User";

@JsonController()
export class UserController {

    @Get("/users")
    get(@EntityFromQuery("id") user: User) {
        return user;
    }

}

@EntityFromCookie

Creates entity from the request cookie.

Example:

import {JsonController, Get} from "routing-controllers";
import {EntityFromCookie} from "typeorm-routing-controllers-extensions";
import {User} from "../entity/User";

@JsonController()
export class UserController {

    @Get("/users")
    get(@EntityFromCookie("userId") user: User) {
        return user;
    }

}

@EntityFromBody

Creates entity from the request body.

Example:

import {JsonController, Post} from "routing-controllers";
import {EntityFromBody} from "typeorm-routing-controllers-extensions";
import {User} from "../entity/User";

@JsonController()
export class UserController {

    @Post("/users")
    save(@EntityFromBody() user: User) {
        return this.userRepository.persist(user);
    }

}

@EntityFromBodyParam

Creates entity from the request's body parameter.

Example:

import {JsonController, Post} from "routing-controllers";
import {EntityFromBodyParam} from "typeorm-routing-controllers-extensions";
import {User} from "../entity/User";

@JsonController()
export class UserController {

    @Post("/users")
    save(@EntityFromBodyParam("user") user: User) {
        return this.userRepository.persist(user);
    }

}

Decorators Options

Each decorator accepts EntityParamOptions which has following options:

  • connection?: string

Name of the connection to be used in TypeORM. By default, its "default" connection.

  • required: boolean

Indicate if this parameter's value is required. If its required and client didn't pass a value, routing-controllers will throw an error.

  • parse: boolean

Specifies "parseJson" option to routing-controllers.

  • type: Function

Entity type. Automatically retrieved from entity param's type, but in some cases, for example if you are using array of entities it should be passed explicitly.

  • property: boolean

Property to find by. If not specified, then entity will be fetched by its primary keys.

Samples

Take a look on samples in ./sample for examples of usages.

typeorm-routing-controllers-extensions's People

Contributors

banashek avatar minostro avatar pleerock avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

typeorm-routing-controllers-extensions's Issues

Do postData fields have to be exactly the same as the entity columns in order to use @EntityFromBody()?

I have this entity

@Entity()
export class Post{
    @PrimaryGeneratedColumn()
    post_id: number;

    @Column({type:'string'})
    comment:string;

    @Column({type:'smallint'})
    category:number;

    
    @AfterLoad()
    convertsth(){
    }

    @BeforeInsert()
    async purifyInsert() {
    }

    @BeforeUpdate()
    async purifyUpdate(){
    }
}

It seems that @EntityFromBody won't work when there are extra unrelated fields. The post body has to be entirely the same as the entity. I can't pass extra fields for non database stuff like a form token alongside the entity data or it will throw TypeError: Cannot read property 'prototype' of undefined. Is that true?

------WebKitFormBoundary5ZQxKuZB8zxZpyVo
Content-Disposition: form-data; name="post_id"

11
------WebKitFormBoundary5ZQxKuZB8zxZpyVo
Content-Disposition: form-data; name="comment"

some comment.....

------WebKitFormBoundary5ZQxKuZB8zxZpyVo
Content-Disposition: form-data; name="category"

2

------WebKitFormBoundary5ZQxKuZB8zxZpyVo
Content-Disposition: form-data; name="token"

dfsfdsdsfdsfdfsdsf

Error:

TypeError: Cannot read property 'prototype' of undefined
    at Broadcaster.isAllowedListener (/home/node/src/subscriber/Broadcaster.ts:247:71)
    at /home/node/src/subscriber/Broadcaster.ts:58:92
    at Array.filter (native)
    at Broadcaster.<anonymous> (/home/node/src/subscriber/Broadcaster.ts:58:14)
    at step (/home/node/node_modules/typeorm/subscriber/Broadcaster.js:32:23)
    at Object.next (/home/node/node_modules/typeorm/subscriber/Broadcaster.js:13:53)
    at /home/node/node_modules/typeorm/subscriber/Broadcaster.js:7:71
    at __awaiter (/home/node/node_modules/typeorm/subscriber/Broadcaster.js:3:12)
    at Broadcaster.broadcastBeforeInsertEvent (/home/node/node_modules/typeorm/subscriber/Broadcaster.js:104:16)
    at /home/node/src/subscriber/Broadcaster.ts:31:67
    at Array.map (native)
    at Broadcaster.<anonymous> (/home/node/src/subscriber/Broadcaster.ts:31:47)
    at step (/home/node/node_modules/typeorm/subscriber/Broadcaster.js:32:23)
    at Object.next (/home/node/node_modules/typeorm/subscriber/Broadcaster.js:13:53)
    at /home/node/node_modules/typeorm/subscriber/Broadcaster.js:7:71
    at __awaiter (/home/node/node_modules/typeorm/subscriber/Broadcaster.js:3:12)
    at Broadcaster.broadcastBeforeEventsForAll (/home/node/node_modules/typeorm/subscriber/Broadcaster.js:57:16)
    at SubjectOperationExecutor.<anonymous> (/home/node/src/persistence/SubjectOperationExecutor.ts:111:47)
    at step (/home/node/node_modules/typeorm/persistence/SubjectOperationExecutor.js:32:23)
    at Object.next (/home/node/node_modules/typeorm/persistence/SubjectOperationExecutor.js:13:53)
    at fulfilled (/home/node/node_modules/typeorm/persistence/SubjectOperationExecutor.js:4:58)
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

Error while Starting the express app

MetadataArgsStorage_1.defaultMetadataArgsStorage.params.push({

TypeError: Cannot read property 'params' of undefined
I'm trying to start the express application. I have created model and the controller but getting error.

String parameters cause ParameterParseJsonError in routing-controllers when using EntityFromParam.

Using a parameter with a string as a value when using EntityFromParameter causes a ParameterParseJsonError to be thrown in routing-controllers.

I've dug down and found out this is because routing-controllers sees the parameters type as the type of entity you're trying to pull back and sets isTargetObject to true in ActionParameterHandler. Causing it to be parsed as a JSON object.

I've made a fix that resolves the issue by setting explicitType to "string" in the decorator, which forces the value to be parsed as a string. This seems to work for both string and number types as the parameter.

Error
    at new HttpError (routing-controllers-id-bug/dist/routing-controllers/src/http-error/HttpError.js:16:22)
    at new BadRequestError (routing-controllers-id-bug/dist/routing-controllers/src/http-error/BadRequestError.js:9:9)
    at new ParameterParseJsonError (routing-controllers-id-bug/dist/routing-controllers/src/error/ParameterParseJsonError.js:9:9)
    at ActionParameterHandler.parseValue (routing-controllers-id-bug/dist/routing-controllers/src/ActionParameterHandler.js:127:23)
    at ActionParameterHandler.normalizeParamValue (routing-controllers-id-bug/dist/routing-controllers/src/ActionParameterHandler.js:111:34)
    at ActionParameterHandler.handle (routing-controllers-id-bug/dist/routing-controllers/src/ActionParameterHandler.js:35:28)
    at actionMetadata.params.sort.map.param (routing-controllers-id-bug/dist/routing-controllers/src/RoutingControllers.js:87:49)
    at Array.map (<anonymous>)
    at RoutingControllers.executeAction (routing-controllers-id-bug/dist/routing-controllers/src/RoutingControllers.js:87:14)
    at driver.registerAction (routing-controllers-id-bug/dist/routing-controllers/src/RoutingControllers.js:59:33)

Support passing class-validator options in decorators

Using a combination of typeorm, routing-controllers, this package, and class-validator decorators.

Trying @EntityFromBody() on a PUT request with some properties missing results in a validation error for the missing properties.

The decorators should pass through a validate property with ValidatorOptions

Argument obtained from @EntityFromBody has no own properties

I know I have used EntityFromBody successfully before, but now every time I debug my requests, the parameter marked with EntityFromBody is an object and has the right constructor, but it has none of its own properties on it. I cannot figure out what I'm doing wrong. I have tried sending requests as both { "prop": "val", ... } and { "controllerParameterName": { "prop": "val", ... } } and have gotten the same results.

Edit: I will go ahead and mention that I double checked and I do have emitDecoratorMetadata set to true in my tsconfig.json.

Question - post body with relationship

Like this post handler, if Post has a relationship like Category, does it support and how to make request?

    @HttpPost("/posts")
    save(@EntityFromBody() post: Post) {
        return this.postRepository.save(post);
    }

EntityFromBody does not work params undefined

Hello,

I have the following controller:

@JsonController("/countries")
export class CountriesController {
private countryRepository: Repository<Country>;
constructor() {
    this.countryRepository = getEntityManager().getRepository(Country);
}
@Get()
getAll() {
return this.countryRepository.find();
}
@Get("/:id")
getOne(@Param("id") id: number) {
return this.countryRepository.createQueryBuilder("country").leftJoinAndSelect("country.specialities","speciality")
    .leftJoinAndSelect("country.thingsToNote","thingToNote").where("country.id = :id", {id}).getOne();
}

@Post("/:id")
@Authorized()
    create(@EntityFromBody() country: Country, @Res() res: Response) {
if(country) {
   return this.countryRepository.persist(country);
} else {
    res.send("No information provided")
}
}
}

It does not compile with the following error:

node_modules\typeorm-routing-controllers-extensions\decorators\EntityFromBody.js:15
        MetadataArgsStorage_1.defaultMetadataArgsStorage.params.push({
                                                        ^

TypeError: Cannot read property 'params' of undefined
    at C:\Users\Chris\Documents\acropolis\node_modules\typeorm-routing-controllers-extensions\decorators\EntityFromBody.js:15:57
    at C:\Users\Chris\Documents\acropolis\routes\countries.js:12:37
    at DecorateProperty (C:\Users\Chris\Documents\acropolis\node_modules\reflect-metadata\Reflect.js:530:29)
    at Object.decorate (C:\Users\Chris\Documents\acropolis\node_modules\reflect-metadata\Reflect.js:100:20)
    at __decorate (C:\Users\Chris\Documents\acropolis\routes\countries.js:4:92)
    at Object.<anonymous> (C:\Users\Chris\Documents\acropolis\routes\countries.js:52:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)

````
Could it be that there is a bug there and that the array params needs to be instantiated first?

Thanks a lot,
Christian

Example doesn't bind any controllers

Not sure if this is intended, but the example here calls createApplication without binding any controllers.

Is it supposed to work purely off of reading the entites defined in createConnection?

for anyone wondering changing

createExpressServer().listen(3000);

to

createExpressServer({
    controllers: [
        PostController
    ]
}).listen(3000);

will do the trick (along with the appropriate import at the top

How to make a static folder

i am using this project to develop,orm part is awesome,but how to make a static folder mapping such as "public" or "static"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.