TypeORM with JS

Viewed 1178

I wanted to use TypeORM with my express app which is in JS and not TS.

Firstly is this possible?

If yes, then when I try using TypeORM I run into the following error:

@Entity()
^

SyntaxError: Invalid or unexpected token
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:599:28)

My entity file - Users.js

const typeorm = require("typeorm");
const Entity = typeorm.Entity;
const Column = typeorm.Column;
const PrimaryGeneratedColumn = typeorm.PrimaryGeneratedColumn;

@Entity()
module.exports = class Users {
    @PrimaryGeneratedColumn
    id: Number;

    @Column()
    name: String;
}

What can be done to fix this?

1 Answers

Decorators like @Entity are TS feature, for js you need to use EntitySchema class instead.

More examples you can find here: https://github.com/typeorm/javascript-example. But please keep in mind that it's not well tested in js.

const EntitySchema = require("typeorm").EntitySchema; // import {EntitySchema} from "typeorm";
const Category = require("../model/Category").Category; // import {Category} from "../model/Category";

module.exports = new EntitySchema({
    name: "Category",
    target: Category,
    columns: {
        id: {
            primary: true,
            type: "int",
            generated: true
        },
        name: {
            type: "varchar"
        }
    }
});
Related