ts-pg-orm
v5.1.7
Published
Typescript PostgreSQL ORM
Downloads
74
Maintainers
Readme
Overview
ts-pg-orm provides PostgreSQL persistence for your Typescript application. Write expressive, zero guess-work, fully type-enforced typescript queries to perform CRUD operations on PostgreSQL databases.
Start by viewing the Getting Started guide.
ts-pg-orm is available on npm.
Usage Overview
Define data formats, relations, and database connectivity to create type-safe auto-completing data stores:
import { createDataFormat, createTsPgOrm, ... } from 'ts-pg-orm'
const userDF = createDataFormat(...)
const ORM = createTsPgOrm([userDF, ...] as const).setRelations([...] as const)
const orm = await ORM.connect({ host: 'localhost', port: 5432, ... })
await orm.provisionStores()
Perform CRUD operations on data stores:
// Create
const userCreated = await orm.stores.user.create({ name: 'alice' })
// Get
const userFound = await orm.stores.user.get({
fields: ['name'],
filter: { field: 'id', op: Operator.EQUALS, val: 1 },
relations: { // Recursively include related data
userGroups: {
query: { ... },
relations: { ... }
},
},
})
// Update
const userUpdated = await orm.stores.user.update({
query: {
filter: { ... },
},
record: { name: 'bob' },
return: true,
})
// Delete
const userDeleted = await orm.stores.user.delete({
query: {
filter: { ... },
},
return: true,
})
Create types to use throughout your application:
export type UserRecord = ToRecord<typeof USER_DFD>
// { id: number, name: string, ... }
export type CreateUserRecordOptions = CreateRecordOptions<typeof USER_DFD>
// { name: string, ... }
export type UserGroupRecord = ToRecord<typeof USER_GROUP_DFD>
// { id: number, name: string, ... }
Use type-enforced sql information to create bespoke SQL statements:
const userSql = ORM.dataFormats.user.sql
const customUserSql = `select ${userSql.columnNames.name} from ${userSql.tableName}`
Examples
Integration Tests
The integration test suite connects to a real PostgreSQL server at (by default) postgres@localhost:5432 and performs various ts-pg-orm queries with a set of example data formats and relations.
Run npm run integration-tests
to build and run these. The database connection configuration is at /.env-cmdrc.json
.
If you found this package delightful, feel free to buy me a coffee ✨