npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ttoss/postgresdb

v0.2.10

Published

A library to handle PostgreSQL database connections and queries

Downloads

482

Readme

@ttoss/postgresdb

This package uses Sequelize to provide a simple framework for working with PostgreSQL databases.

Installation

pnpm add @ttoss/postgresdb
pnpm add -D @ttoss/postgresdb-cli

ESM only

This package is ESM only. Make sure to use it in an ESM environment.

{
  "type": "module"
}

Usage

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:

docker run --name postgres-test -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres

If you want to use Docker Compose, you can create a docker-compose.yml file with the following content:

services:
  db:
    image: postgres
    environment:
      POSTGRES_PASSWORD: mysecretpassword
    volumes:
      - db-data:/var/lib/postgresql/data
    ports:
      - '5432:5432'

volumes:
  db-data:

And run the following command:

docker compose up -d

Create a model

Create a folder called models and add a new file called User.ts with the following content:

import { Table, Column, Model } from '@ttoss/postgresdb';

@Table
export class User extends Model<User> {
  @Column
  declare name: string;

  @Column
  declare email: string;
}

_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:

export { User } from './User';

Create a new instance of the database

Create a new file called src/db.ts with the following content:

import { initialize } from '@ttoss/postgresdb';
import * as models from './models';

export const db = await initialize({ models });

Note: the script sync will use the db object to sync the database schema with the models.

Environment variables

You can set the database connection parameters in two ways:

  1. Defining them in the src/db.ts file using the initialize function.

    export const db = initialize({
      database: '', // database name
      username: '', // database username
      password: '', // database password
      host: '', // database host
      port: 5432, // database port. Default: 5432
      models,
    });
  2. Using environment variables:

    • DB_NAME: database name
    • DB_USERNAME: database username
    • DB_PASSWORD: database password
    • DB_HOST: database host
    • DB_PORT: database port. Default: 5432

    @ttoss/postgresdb will use them automatically if they are defined.

    Here is an example of a .env file:

    DB_NAME=postgres
    DB_USERNAME=postgres
    DB_PASSWORD=mysecretpassword
    DB_HOST=localhost
    DB_PORT=5432

Sync the database schema

To sync the database schema with the models, use the sync command:

pnpm dlx @ttoss/postgresdb-cli sync

By now, you should have a working database with a User table.

This command works by importing the db object from the src/db.ts file and calling the sync method on it.

CRUD operations

You can now use the db object to interact with the database. Check the Sequelize documentation for more information.

import { db } from './db';

const user = await db.User.create({
  name: 'John Doe',
  email: '[email protected]',
});

All models are available in the db object.

Using in a monorepo

If you want to use in a monorepo by sharing the models between packages, you need to create some configurations to make it work.

On the postgresdb package

  1. Create your postgresdb package following the steps above.

  2. Exports your main file in the package.json file:

    {
      "type": "module",
      "exports": "./src/index.ts"
    }
  3. Create a new file called src/index.ts with the following content to exports the models you've created:

    export * as models from './models';

    We recommend to not export the db object in this file because you may want to use different configurations in different packages.

On the other packages

  1. Install @ttoss/postgresdb package:

    pnpm add @ttoss/postgresdb
  2. Add your postgresdb package as a dependency. In the case you're using PNPM, you can use the workspace protocol:

    {
      "dependencies": {
        "@yourproject/postgresdb": "workspace:^"
      }
    }
  3. Include the postgresdb package in the include field of the tsconfig.json file:

    {
      "include": ["src", "../postgresdb/src"]
    }

    This way, you can import the models using the @yourproject/postgresdb package.

  4. Create a new file called src/db.ts with the following content:

    import { initialize } from '@ttoss/postgresdb';
    import { models } from '@yourproject/postgresdb';
    
    export const db = initialize({
      models,
      // other configurations
    });
  5. Use the db object to interact with the database.

API

initialize(options: InitializeOptions): db

Initialize the database connection and load the models.

Options

All Sequelize options 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, i.e., @Table, @Column, @ForeignKey, etc.

Types

ModelColumns<T>

A type that represents the columns of a model.

import { Column, Model, type ModelColumns, Table } from '@ttoss/postgresdb';

@Table
class User extends Model<User> {
  @Column
  declare name?: string;

  @Column
  declare email: string;
}

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