Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an entity passing in an object using typeorm

I have an entity "List" and i want to create a new list by passing in an object into the constructor.

List.ts

import {Entity, PrimaryColumn, Column, CreateDateColumn, UpdateDateColumn, DeleteDateColumn } from "typeorm";

@Entity()
export class List {

    @PrimaryColumn()
    id: string;

    @Column({type: "varchar", nullable: true})
    dtype: string;

    @Column({type: "varchar", nullable: true})
    title: string;

    @Column({type: "varchar"})
    user_id: string;

    @Column({type: "varchar", nullable: true})
    brand_id: string;

    @CreateDateColumn({type: "timestamp", nullable: true})
    created_at: string;

    @UpdateDateColumn({type: "timestamp", nullable: true})
    updated_at: string;

    @DeleteDateColumn({type: "timestamp", nullable: true})
    deleted_at: string;

}

list.test

import "reflect-metadata";
import {createConnection, getRepository} from "typeorm";
import {List} from "./../../src/entity/lists/List";

describe("List", () => {

    let connection
    beforeAll( async () => {
        connection = await createConnection();
        console.log(connection);
    });

    it("should insert a list into database", async () => {

        const listRepository = getRepository(List);

        const list = new List({
            id: "7e60c4ef",
            dtype: "brandlist",
            title: "OnePlus",
            user_id: "3aecd1b0-c34d-4427-9abd-fdacef00eaa5",
            brand_id: "7e60c4ef-0e6f-46c9-948b-a97d555bf4e4",
        });

    })

})

Right now i get the following

Expected 0 arguments, but got 1.ts(2554)

Is there a way typeorm can automatically handles this?

like image 497
Kay Avatar asked Jun 01 '20 10:06

Kay


People also ask

What is getRepository TypeORM?

Repository is specific to an entity. In other words, each entity will have its own, build-in repository and it can be accessed using getRepository() method of connection object as specified below − const studRepository = manager.

Is TypeORM only for TypeScript?

TypeORM can be used not only with TypeScript, but also with JavaScript. Everything is the same, except you need to omit types and if your platform does not support ES6 classes then you need to define objects with all required metadata.

How to inform typeorm about the entities in the database?

Based on the definition in the Entity class, TypeORM will create the corresponding table in the database. To inform TypeORM about our entities, we need to add the entity in the DataSource object as below.

How to use object initializer in typescript?

In Typescript if you want to use Object Initializer you need to define all properties in the class. let category: Category = { name: '', description: '' }; With this way your model still can be remain as an interface.

How to use *simple-array column type in typeorm?

Advanced relational database supports array datatype. To support the array datatype, TypeORM provides a special column type, *simple-array" to store primitive array values. A sample code to use it is as follows − @Entity() export class Student { @PrimaryGeneratedColumn() id: number; @Column("simple-array") names: string[]; }

What is @its attribute in typeorm?

Its attributes / member variables refer the corresponding database table’s fields / columns. TypeORM supports all type of database fields through Column class. Let us learn the different type of column supported by TypeORM in this chapter. @Column () decorator class is used to represent the column and its type in the entity.


2 Answers

There are two ways to solve this, the first is to declare your own constructor in the List class and assign the values but it gets messy.

The preferred method is by using repository.create to create an instance of the entity from an object. https://github.com/typeorm/typeorm/blob/master/docs/repository-api.md

        const listRepository = connection.getRepository(List);

        const list = listRepository.create({
            id: "7e60c4ef",
            dtype: "brandlist",
            title: "OnePlus",
            user_id: "3aecd1b0-c34d-4427-9abd-fdacef00eaa5",
            brand_id: "7e60c4ef-0e6f-46c9-948b-a97d555bf4e4",
        });

        const newList = await listRepository.save(list);
like image 145
Kay Avatar answered Nov 15 '22 02:11

Kay


Edit: I did arrive at this thread by trying to search how to initialize a TypeORM object/class by passing attributes/body params/object. So, if you need a single object you can use the manager.

import { getManager } from "typeorm";
// ...
const manager = getManager();
const newUser = manager.create(User, req.body);
const user = await manager.save(newUser);

Example creating a user object and saving it from an express request dynamic body. This example is just to illustrate. Validate and sanitize your schema before passing it to the create function to avoid allowing the API user to pass any parameter like {admin: true} ;).

import { getManager } from "typeorm";
createConnection()
  .then(async (connection) => {
    const app = express();
    app.use(express.json());

    app.post("/users", async (req: Request, res: Response) => {
      const manager = getManager();
      const newUser = manager.create(User, req.body);
      const user = await manager.save(newUser);
      res.json(user);
    });

    app.listen(4000);
  })
  .catch((error) => console.log(error));
like image 26
Sadjow Avatar answered Nov 15 '22 04:11

Sadjow