Skip to content

GraphQL over TypeORM

A deep dive into the graphql-typeorm-sql starter: one class as TypeORM entity and GraphQL object type, a resolver inside a feature module, async field resolution, transactions on the REST side, and a database-free schema test.

6 min read Source

Source: graphql-typeorm-sql

Where Code-first GraphQL keeps its data in memory, this starter puts the same schema on Postgres. It is the most complete application in the set: migrations, a transactional REST write, a GraphQL query, OpenAPI for the REST half and a schema test that needs no database.

The central idea is that one class is the persistence entity and the GraphQL type at the same time. There is no DTO layer, no mapper and no second schema definition to keep in sync.

Project layout

src
├─ app.module.ts                                  # imports PgModule
├─ app.controller.ts                              # GET / health check
├─ bootstrap.ts                                   # pipeServer → pipeGraphQL → pipeSwagger
├─ graphql-schema.spec.ts                         # prints the schema, no database
├─ swagger.spec.ts                                # asserts the OpenAPI document
└─ modules/data-store
   ├─ pg.module.ts                                # controller + resolver + service + datasource
   ├─ entity/user.entity.ts                       # @Entity + @ObjectType + @ApiSchema
   ├─ services/user.service.ts
   ├─ transactional.interceptor.ts                # same pattern as the REST starter
   ├─ controllers/rest/user.controller.ts         # GET/POST /users
   ├─ controllers/graphql/user.resolver.ts        # Query users
   └─ configs
      ├─ pgdatasource.config.ts
      ├─ pgdatasource.logger.config.ts
      └─ pgdatasource.cli.ts                      # datasource for migrations

One class, three consumers

@Entity()
@ObjectType()
@ApiSchema({name: "User"})
export class User {

  @PrimaryGeneratedColumn()
  @Field()
  @ApiProperty({example: 1, readOnly: true})
  id: number;

  @Column()
  @Field()
  @ApiProperty({example: "Igor"})
  firstName: string;
}
Decorator Consumer Effect
@Entity, @Column TypeORM table and column metadata, used by the DataSource
@ObjectType, @Field GraphQL type User { id: Float! firstName: String! … }
@ApiSchema, @ApiProperty OpenAPI components.schemas.User

All three are metadata. Nothing runs until a consumer reads it: pipeServer builds the DataSource from the TypeORM metadata, pipeGraphQL builds the schema from the GraphQL metadata, pipeSwagger builds the document from the route and OpenAPI metadata. That is why the three can coexist on one class without fighting each other.

The trade-off is honest to point out: the database shape and the API shape become the same shape. For a starter that is exactly what you want; for a large system you may eventually want a separate projection type, and this structure makes that decision explicit rather than hiding it behind a mapper.

The resolver lives in the feature module

@Module({
  controllers: [UserController],
  providers: [
    PgDataSource,
    UserService,
    UserResolver
  ]
})
export class PgModule {
}
@Injectable()
@Resolver()
export class UserResolver {
  @Inject() userService: UserService;

  @Query(() => [User])
  async users(): Promise<Array<User>> {
    return await this.userService.find();
  }
}

Two points:

  • The resolver sits next to the service it uses, in providers of PgModule, not in the root module. pipeGraphQL walks the whole module graph, so a resolver declared in an imported feature module is picked up. Feature-local resolvers keep the GraphQL surface and the REST surface of the same domain in one place.
  • @Query(() => [User]) is required even though the return type is declared, because the return type is Promise<Array<User>>. At runtime the reflected type of an async method is Promise, which carries no element type — hence the explicit thunk.

Same data, two protocols

Method Path Uses
GET / health check
GET /users UserService.find()
POST /users transaction via @Transactional(User)
POST /users-default-transaction UserService.save()
POST /graphql UserResolver.users
GET /graphql/schema.graphql SDL
GET /docs OpenAPI for the REST routes

Because both surfaces inject the same UserService from the same injector, a transaction opened on the REST side and a query on the GraphQL side share the connection pool and the same entity metadata. There is no second application to configure.

The transaction interceptor is identical to the one explained in REST API on Postgres: it creates a query runner, overrides the Repository token in the request scope, and commits or rolls back. Reusing the same pattern here is the point — it is application code, not framework magic, so it travels.

Testing the schema without a database

This is the pattern worth stealing. GraphQLModule.printSchema(AppModule) builds the schema from the module class and returns SDL, with no socket and no DataSource connection:

const schema = GraphQLModule.printSchema(AppModule);

expect(schema).toContain("users: [User!]!");
expect(schema).toContain("type User {");
expect(schema).toContain("id: Float!");

A schema regression — a field losing its decorator, a return type changing shape, a resolver no longer being a provider — fails a test that runs in milliseconds and needs no infrastructure. Pair it with the OpenAPI document test and both contracts are locked without opening a port.

File Kind Proves
graphql-schema.spec.ts build-time the GraphQL schema shape
swagger.spec.ts build-time the REST document and User component
app.controller.spec.ts unit health check handler

Running against Postgres

cd resty-starters
docker compose up -d --wait      # postgres on 5432, database typeix, postgres/admin
cd graphql-typeorm-sql
npm install
npm run build && npm run start

api-typeorm-sql uses the same database and the same migration, so both starters can run against this one instance and share the local dataset.

ormconfig.json has migrationsRun: true, so the first boot creates the table and inserts the seed rows. A verified round trip:

GET  /users      → [{"id":1,"firstName":"Igor",…},{"id":2,…}]
POST /users      → {"age":100,"firstName":"Igor","lastName":"Surname","id":3}
POST /graphql    → {"data":{"users":[{"id":1,"firstName":"Igor"}, …]}}
GET  /docs       → 200, paths: /, /users, /users-default-transaction

Pitfalls

async resolvers always need an explicit type

@Query(() => [User]) on async users(): Promise<Array<User>> is not redundant. The reflected type is Promise, and a thunk-less @Query() would fail to resolve the field type. The same applies to any async field in an @ObjectType.

  • The entity must be in the DataSource globs. ormconfig.json points at dist/modules/data-store/entity/**/*.js, so running from source without a build gives "No metadata for User" on the first query.
  • GraphQL is absent from OpenAPI by design. /graphql is piped onto the server, not a controller, so the document covers only the REST routes.
  • Float! for ids. As in Code-first GraphQL, numeric ids map to Float!; the schema test pins that so a change is deliberate.
  • The migration CLI needs its own datasource — see pgdatasource.cli.ts; -d is mandatory in TypeORM 1.x.

Choosing between this and the in-memory GraphQL starter

You want to learn Read
GraphQL concepts — types, arguments, parent, interceptors ts-graphql
GraphQL on a real database, with migrations and transactions this page
REST and GraphQL sharing one entity this page

Next: Server-rendered app with uploads leaves JSON behind entirely.