marcobiedermann
marcobiedermann

Reputation: 4933

TypeORM return plain object

How do I return a plain JavaScript object from TypeORM Repository functions like find, create, update or delete?

const user = User.findOne({ where: { id: 1 } }); 

Actual:

User | undefined

{
  User: {
    id: 1
  }
}

Instead I would like to receive a plain object independent from any library / framework

Expected:

{
  id: 1
}

This way it would be easier to be framework independent and your repository calls could be interchangeable at any point of time without rewriting the entire application and not to depend on third party scripts that heavily.

Sequelize for example has an option { plain: true }

Upvotes: 4

Views: 11036

Answers (2)

Paweł Święcicki
Paweł Święcicki

Reputation: 1

Without class-transformer it is actually quite easy to create a simple method like this:

entityToObject<T>(entity: T): T {
    return Object.assign({}, entity);
}

than use it on findOne returned object like so:

async view_user(id: number): Promise<User|null> {
    const user = await this.repository.findOne({where: {id}});
    if(!user) {
        throw Error("User not found");
    }
    return this.entityToObject<User>(user);
}
entityToObject<T>(entity: T): T {
    return Object.assign({}, entity);
}

Upvotes: 0

zenbeni
zenbeni

Reputation: 7223

You can easily use the class-transformer library to produce plain objects from entity instances:

https://github.com/typestack/class-transformer

const user = repository.findOne({ where: { id: 1 } });
const plain = classToPlain(user);

Another way is to use queryBuilder API and returns raw results from the database

const rawResult = repository.createQueryBuilder("user")
    .select("user")
    .where("user.id = :id", {id: 1})
    .getRawOne();

The point is why would you want to do so? Entity is first citizen in TypeOrm so you want that any change on its structure should generate compile errors if something is not back compatible. Using plain objects would hide contract changes, and you would discover errors only at runtime, not sure if it is an optimal way to work with TypeOrm to my mind.

Upvotes: 4

Related Questions