Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@ttoss/postgresdb

Package Overview
Dependencies
Maintainers
2
Versions
51
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ttoss/postgresdb - npm Package Compare versions

Comparing version
0.2.22
to
0.2.23
+3
-3
package.json
{
"name": "@ttoss/postgresdb",
"version": "0.2.22",
"version": "0.2.23",
"description": "A library to handle PostgreSQL database connections and queries",

@@ -18,4 +18,4 @@ "license": "MIT",

".": {
"import": "./dist/esm/index.js",
"types": "./dist/index.d.ts"
"types": "./dist/index.d.ts",
"default": "./dist/esm/index.js"
}

@@ -22,0 +22,0 @@ },

+87
-134
# @ttoss/postgresdb
This package uses [Sequelize](https://sequelize.org/) to provide a simple framework for working with PostgreSQL databases.
A lightweight [Sequelize](https://sequelize.org/) wrapper for PostgreSQL databases with TypeScript support.

@@ -12,18 +12,10 @@ ## Installation

### ESM only
**ESM only**: Add `"type": "module"` to your `package.json`.
This package is [ESM only](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). Make sure to use it in an ESM environment.
## Quick Start
```json
{
"type": "module"
}
```
### Database Setup
## Usage
Use Docker to create a PostgreSQL instance:
### Setup the database
If you already have a database, you can skip this step. If you don't, you can use the following Docker command to create a new PostgreSQL database on port 5432 using Docker:
```bash

@@ -33,3 +25,3 @@ docker run --name postgres-test -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres

If you want to use [Docker Compose](https://docs.docker.com/compose/), you can create a `docker-compose.yml` file with the following content:
Or with Docker Compose (`docker-compose.yml`):

@@ -51,4 +43,2 @@ ```yaml

And run the following command:
```bash

@@ -58,5 +48,5 @@ docker compose up -d

### Create a model
### Define Models
Create a folder called `models` and add a new file called `User.ts` with the following content:
Create `models/User.ts`:

@@ -74,8 +64,8 @@ ```typescript

}
_This packages exports all decorators from [sequelize-typescript](https://github.com/sequelize/sequelize-typescript), so you can use them to define your models._
```
Export the model in the `models/index.ts` file:
_All [sequelize-typescript](https://github.com/sequelize/sequelize-typescript) decorators are available._
Export in `models/index.ts`:
```typescript

@@ -85,5 +75,5 @@ export { User } from './User';

### Create a new instance of the database
### Initialize Database
Create a new file called `src/db.ts` with the following content:
Create `src/db.ts`:

@@ -97,45 +87,33 @@ ```typescript

_Note: the script [`sync`](#sync-the-database-schema) will use the `db` object to sync the database schema with the models._
### Configuration
### Environment variables
**Option 1 - Direct configuration:**
You can set the database connection parameters in two ways:
```typescript
export const db = initialize({
database: 'mydb',
username: 'user',
password: 'pass',
host: 'localhost',
port: 5432,
models,
});
```
1. Defining them in the `src/db.ts` file using the `initialize` function.
**Option 2 - Environment variables (`.env`):**
```typescript
export const db = initialize({
database: '', // database name
username: '', // database username
password: '', // database password
host: '', // database host
port: 5432, // database port. Default: 5432
models,
});
```
```env
DB_NAME=postgres
DB_USERNAME=postgres
DB_PASSWORD=mysecretpassword
DB_HOST=localhost
DB_PORT=5432
```
2. Using environment variables:
Environment variables are automatically used if defined.
- `DB_NAME`: database name
- `DB_USERNAME`: database username
- `DB_PASSWORD`: database password
- `DB_HOST`: database host
- `DB_PORT`: database port. Default: 5432
### Sync Schema
`@ttoss/postgresdb` will use them automatically if they are defined.
[Synchronize](https://sequelize.org/docs/v6/core-concepts/model-basics/#model-synchronization) database schema with models:
Here is an example of a `.env` file:
```env
DB_NAME=postgres
DB_USERNAME=postgres
DB_PASSWORD=mysecretpassword
DB_HOST=localhost
DB_PORT=5432
```
### Sync the database schema
To [sync](https://sequelize.org/docs/v6/core-concepts/model-basics/#model-synchronization) the database schema with the models, use the [`sync` command](https://ttoss.dev/docs/modules/packages/postgresdb-cli/):
```bash

@@ -145,10 +123,8 @@ pnpm dlx @ttoss/postgresdb-cli sync

By now, you should have a working database with a `User` table.
This imports `db` from `src/db.ts` and syncs the schema.
This command works by importing the `db` object from the `src/db.ts` file and calling the `sync` method on it.
### CRUD Operations
### CRUD operations
All models are accessible via the `db` object. See [Sequelize documentation](https://sequelize.org/master/manual/model-querying-basics.html) for complete query API.
You can now use the `db` object to interact with the database. Check the [Sequelize documentation](https://sequelize.org/master/manual/model-querying-basics.html) for more information.
```typescript

@@ -163,93 +139,75 @@ import { db } from './db';

All models are available in the `db` object.
## Monorepo Usage
### Using in a monorepo
Share models across packages with this setup:
If you want to use in a monorepo by sharing the models between packages, you need to create some configurations to make it work.
**In the database package (`@yourproject/postgresdb`):**
#### On the `postgresdb` package
`package.json`:
1. Create your `postgresdb` package following the steps above.
```json
{
"type": "module",
"exports": "./src/index.ts"
}
```
1. Exports your main file in the `package.json` file:
`src/index.ts`:
```json
{
"type": "module",
"exports": "./src/index.ts"
}
```
```typescript
export * as models from './models';
```
1. Create a new file called `src/index.ts` with the following content to exports the `models` you've created:
_Don't export `db` here - each package may need different configurations._
```typescript
export * as models from './models';
```
**In consuming packages:**
_We recommend to not export the `db` object in this file because you may want to use different configurations in different packages._
Add dependencies to `package.json`:
#### On the other packages
```json
{
"dependencies": {
"@ttoss/postgresdb": "^x.x.x",
"@yourproject/postgresdb": "workspace:^"
}
}
```
1. Install `@ttoss/postgresdb` package:
Update `tsconfig.json`:
```bash
pnpm add @ttoss/postgresdb
```
```json
{
"include": ["src", "../postgresdb/src"]
}
```
1. Add your `postgresdb` package as a dependency. In the case you're using PNPM, you can use the [workspace protocol](https://pnpm.io/workspaces#workspace-protocol-workspace):
Create `src/db.ts`:
```json
{
"dependencies": {
"@yourproject/postgresdb": "workspace:^"
}
}
```
```typescript
import { initialize } from '@ttoss/postgresdb';
import { models } from '@yourproject/postgresdb';
1. Include the `postgresdb` package in the `include` field of the `tsconfig.json` file:
export const db = initialize({ models });
```
```json
{
"include": ["src", "../postgresdb/src"]
}
```
## API Reference
_This way, you can import the models using the `@yourproject/postgresdb` package._
### `initialize(options)`
1. Create a new file called `src/db.ts` with the following content:
Initializes database connection and loads models.
```typescript
import { initialize } from '@ttoss/postgresdb';
import { models } from '@yourproject/postgresdb';
**Options:** All [Sequelize options](https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#instance-constructor-constructor) except `dialect` (always `postgres`), plus:
export const db = initialize({
models,
// other configurations
});
```
- `models` (required): Object mapping model names to model classes
1. Use the `db` object to interact with the database.
### Decorators
## API
All [sequelize-typescript](https://www.npmjs.com/package/sequelize-typescript) decorators are exported: `@Table`, `@Column`, `@ForeignKey`, etc.
### `initialize(options: InitializeOptions): db`
### Types
Initialize the database connection and load the models.
#### `ModelColumns<T>`
#### Options
Extracts column types from a model:
All [Sequelize options](https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#instance-constructor-constructor) are available, expect `models`.
- `models`: An object with all models to be loaded. The keys are the model names, and the values are the model classes. This way, you can access the models using the `db` object.
### Sequelize decorators
This package exports all decorators from [sequelize-typescript](https://www.npmjs.com/package/sequelize-typescript), i.e., `@Table`, `@Column`, `@ForeignKey`, etc.
## Types
### `ModelColumns<T>`
A type that represents the columns of a model.
```typescript

@@ -267,9 +225,4 @@ import { Column, Model, type ModelColumns, Table } from '@ttoss/postgresdb';

/**
* UserColumns = {
* name?: string;
* email: string;
* }
*/
// Inferred type: { name?: string; email: string; }
type UserColumns = ModelColumns<User>;
```