Search code examples
typeorm

Is there a way (or best practice) to share my TypeORM models with the frontend of my code without complete duplication?


I would like to use the entities I created with TypeORM in the front-end as well. Is there a clean way of doing this? Or should I keep proceeding as I am.

At this point, my file structure looks as so (Angular 8 on the front-end):

/server
  /entity
    ExampleEntity.ts
/app
  /entity
    Example.ts

They both have the same content, but the front-end one is lacking all TypeORM constructs.


Solution

  • There's a shim you can use to prevent errors on undefined decorators when sharing the same models across backend and frontend. Simply define the following in your (front-end specific) tsconfig.json:

    {
      ...
      "compilerOptions": {
        ...
        "paths": {
          "typeorm": ["./node_modules/typeorm/typeorm-model-shim.js"]
        }
      }
    }
    

    This overrides module resolution for typeorm to point the shim instead. Check here for a related issue in the TypeORM repo.

    Having said that, generally I'd lean towards maintaining separate models for backend and frontend just as you have, as in my experience the two end up diverging at some point anyway: TypeORM entities often contain implementation details you might not want to spill over to the frontend etc. Of course your mileage may vary and the shim is there when you need it!