REST API on Postgres¶
A deep dive into the api-typeorm-sql starter: modules with exported providers, an async TypeORM DataSource provider, a transactional request interceptor, migrations and OpenAPI annotations.
Source: api-typeorm-sql
This is the starter to read first. It is a complete JSON API with a database, and it touches every layer of the framework once: a root module, a feature module with exports, an async provider, a controller, a request interceptor that opens a transaction, migrations, tests and OpenAPI documentation.
Two routes of this starter (POST /users and POST /users-default-transaction) create the same row, one inside an explicit transaction and one through the default path. Comparing them is the fastest way to understand how request interceptors compose with dependency injection.
Project layout¶
src
├─ app.controller.ts # routes: GET /, GET /users, POST /users, ...
├─ app.module.ts # root module: imports PgModule
├─ bootstrap.ts # pipeServer + pipeSwagger
├─ ormconfig.json # shared connection settings (dist globs)
├─ swagger.spec.ts # asserts the generated document, no database
└─ modules/data-store
├─ pg.module.ts # feature module, exports its providers
├─ entity/user.entity.ts # TypeORM entity + @ApiSchema/@ApiProperty
├─ services/user.service.ts # repository access
├─ transactional.interceptor.ts # query runner per request
├─ migration/1621192879101-User.ts # table + seed rows
└─ configs
├─ pgdatasource.config.ts # async DataSource provider
├─ pgdatasource.logger.config.ts # TypeORM logger bridged to @typeix/logger
└─ pgdatasource.cli.ts # DataSource for `typeorm migration:*`
The module graph¶
@RootModule({
imports: [PgModule],
controllers: [AppController],
providers: [AppService],
shared_providers: [/* Logger factory */]
})
export class AppModule {
}
@Module({
providers: [PgDataSource, UserService],
exports: [PgDataSource, UserService]
})
export class PgModule {
}
AppController injects UserService, even though UserService is declared in PgModule rather than in the root module. That works because PgModule exports it: a module sees only what it declares plus what its imported modules export. Removing UserService from exports turns the injection into a resolution error at boot — this is the guard rail that keeps a large application from turning into a global container.
shared_providers vs providers
Logger is declared in shared_providers of the root module, so one instance is created once and handed to every module that asks for it. providers would create a module-local instance. Logging is the typical case: you want one transport, not one per module.
See Modules and the Dependency Graph for the full resolution rules.
The database as a provider¶
The starter does not connect to Postgres in bootstrap.ts. It wraps the connection in a provider, so the connection is created by the injector, can depend on other providers, and is torn down with the application:
@Injectable()
export class PgDataSource {
@CreateProvider({
provide: DataSource,
useFactory: async (logger: Logger) => {
return await new DataSource(<DataSourceOptions>{
...pgConfig,
logging: process.env.NODE_ENV !== "prod",
logger
}).initialize();
},
providers: [PgDataSourceLogger, Injector]
}) private dataSource: DataSource;
getRepository<T>(entity: EntityTarget<T>): Repository<T> {
return this.dataSource.manager.getRepository(entity);
}
}
Four details are worth pausing on:
useFactoryis async. The injector awaits it, so no request can be served beforeDataSource.initialize()has resolved.- The factory declares its own dependencies through
providers: [PgDataSourceLogger, Injector]and takesloggeras an argument. The TypeORM logger is therefore a normal injectable, not a module-level singleton. loggingis switched off forNODE_ENV=prod, which keeps production logs free of every query.- The class exposes
getRepository()instead of leaking theDataSourceto every consumer, so a service never has to know how the connection was built.
The connection settings live in src/ormconfig.json, which both the runtime provider and the migration CLI import. entities and migrations point at compiled files:
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "postgres",
"password": "admin",
"database": "typeix",
"synchronize": false,
"migrationsRun": true,
"entities": ["dist/modules/data-store/entity/**/*.js"],
"migrations": ["dist/modules/data-store/migration/**/*.js"]
}
synchronize: false means the schema is owned by migrations, and migrationsRun: true applies pending ones on boot. That combination is what makes the starter reproducible: npm run build followed by npm run start against an empty database produces the same schema and the same two seed rows every time.
Routes¶
| Method | Path | Handler | Transaction |
|---|---|---|---|
GET | / | getHello | — |
GET | /users | getUsers → UserService.find() | — |
POST | /users | createUser | explicit, READ COMMITTED |
POST | /users-default-transaction | createUserWithDefaultTransactionLevel | none |
@GET("users")
@ApiOperation({summary: "List users", operationId: "getUsers"})
@ApiResponse({status: 200, type: User, isArray: true})
getUsers() {
return this.userService.find();
}
@POST("users")
@ApiOperation({summary: "Create a user inside a transaction", operationId: "createUser"})
@ApiResponse({status: 200, type: User})
@Transactional(User)
createUser(@Inject() repository: Repository<User>) {
const user = new User();
user.age = 100;
user.firstName = "Igor";
user.lastName = "Surname";
return repository.save(user);
}
The handler returns a plain value or a promise; resty serialises it. There is no response object in the signature, and no manual res.json(...).
A transaction per request¶
@Transactional(User) is not a framework feature — it is 30 lines of application code that shows how far request interceptors reach:
@Injectable()
class TransactionalInterceptor implements RequestInterceptor {
@Inject() injector: Injector;
@Inject() config: PgDataSource;
async invoke(request: InterceptedRequest): Promise<any> {
const queryRunner = this.config.getDataSource().createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction("READ COMMITTED");
try {
const type = request.args.type;
const repository: Repository<typeof type> = await queryRunner.manager.getRepository(type);
this.injector.set(Repository, repository);
await request.handler();
await queryRunner.commitTransaction();
} catch {
await queryRunner.rollbackTransaction();
} finally {
await queryRunner.release();
}
}
}
export function Transactional<T>(type: T) {
return addRequestInterceptor(TransactionalInterceptor, {type});
}
The interesting part is this.injector.set(Repository, repository). A request gets its own injector scope; overriding the Repository token there means the controller parameter @Inject() repository: Repository<User> resolves to the repository bound to this query runner, not to the shared DataSource. The controller stays free of transaction plumbing, and the interceptor can be reused for any entity by passing a different type.
Compare the two POST routes in a running application: the transactional one writes inside a READ COMMITTED transaction and rolls back on a thrown error, the other one goes through UserService and commits per statement.
Release the query runner
queryRunner.release() belongs in finally. A leaked runner keeps a pooled connection open and the pool drains under load — a failure mode that only appears after enough requests.
Migrations¶
migration/<timestamp>-<Name>.ts files are generated by the TypeORM CLI, which cannot read the TypeScript provider. That is why the starter ships a second DataSource:
/**
* DataSource used only by the typeorm CLI (migration:run / migration:create).
* The CLI runs against TypeScript sources, so entities and migrations point to src.
*/
export default new DataSource(<DataSourceOptions>{
...config,
logging: false,
entities: ["src/modules/data-store/entity/**/*.ts"],
migrations: ["src/modules/data-store/migration/**/*.ts"],
subscribers: []
});
npx typeorm migration:run -d src/modules/data-store/configs/pgdatasource.cli.ts
npx typeorm migration:create src/modules/data-store/migration/AddUserColumn
TypeORM 1.x removed ormconfig.json CLI discovery, so -d is mandatory; the runtime keeps reading ormconfig.json, the CLI gets the src-flavoured variant.
OpenAPI¶
Documentation is attached where the data lives: @ApiSchema/@ApiProperty on the entity, @ApiTags/@ApiOperation/@ApiResponse on the controller.
@Entity()
@ApiSchema({name: "User"})
export class User {
@PrimaryGeneratedColumn()
@ApiProperty({example: 1, readOnly: true})
id: number;
}
pipeSwagger runs after pipeServer in src/bootstrap.ts and exposes /docs, /docs/openapi.json and /docs/openapi.yaml. Because the document is built from the registered routes, a controller that is not wired into the module graph cannot appear in it.
The spec asserts the document without touching Postgres:
const document = SwaggerModule.createDocument(AppModule, {
info: {title: "TypeORM API", version: "1.0.0"}
});
expect(document.paths["/users"].get.operationId).toEqual("getUsers");
const user = document.components.schemas.User as {properties: Record<string, any>};
expect(Object.keys(user.properties)).toEqual(["id", "firstName", "lastName", "age"]);
Tests¶
| File | Kind | What it proves |
|---|---|---|
src/app.controller.spec.ts | unit | the controller returns what it should, service stubbed |
src/swagger.spec.ts | build-time | the OpenAPI document still contains the routes and the User schema |
test/app.e2e-spec.ts | in-process | a real request through router and injector returns Hello World! |
The e2e test uses fakeHttpServer, so it needs no port and no database for the GET / route:
app = await fakeHttpServer(AppModule);
const response = await app.GET("/");
expect(response.getBody().toString()).toEqual("Hello World!");
Pitfalls found in this starter¶
import * as chalk breaks the query logger
pgdatasource.logger.config.ts must use import chalk = require("chalk"). The CommonJS __importStar helper copies a module through Object.getOwnPropertyNames, and chalk exposes its styles as non-enumerable getters — so chalk.white is undefined and the first logged query throws TypeError: chalk.white is not a function. The symptom only appears once a query runs, which makes it look like a database problem.
- Entity globs are relative to
dist/. Running the compiled app (npm run start:prod) needsnpm run buildfirst, otherwise TypeORM sees no entities and reports "No metadata for User". migrationsRun: trueis a boot-time cost. It applies migrations during provider creation, so the first request waits for it. That is intentional here; in a multi-replica deployment you would run migrations as a separate job.process.cwd()matters.ormconfig.jsonpaths assume the process starts in the project root.
Next: REST API on MongoDB keeps the same shape but swaps the persistence layer — useful for seeing which parts of the design are TypeORM-specific and which are the framework's.