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

prisma-pgtyped-prepared-query

v0.0.1

Published

<div style="display: flex; flex: 0 0 0; justify-content: center; gap: 22px; margin-bottom: 22px;"> <img alt="prisma logo" src="https://raw.githubusercontent.com/prisma/presskit/main/Assets/Prisma-DarkLogo.svg" style="width: 120px; background: white; pad

Downloads

2

Readme

Prisma & Pgtyped client extension

This package exposes a Prisma Client extension to use PgTyped's PreparedQuery.

Installation

$ npm install --save @pgtyped/runtime @prisma/client prisma prisma-pgtyped-prepared-query
$ npm install --save-dev typescript @pgtyped/cli
$ pnpm add --save @pgtyped/runtime @prisma/client prisma prisma-pgtyped-prepared-query
$ pnpm add --save-dev typescript @pgtyped/cli
$ yarn add @pgtyped/runtime @prisma/client prisma prisma-pgtyped-prepared-query
$ yarn add --dev typescript @pgtyped/cli

Usage

See the packages/example folder

To use the extension, you need to call $extends on your Prisma client:

// prisma-client.ts
import { prismaPgtypedPreparedQuery } from "prisma-pgtyped-prepared-query";

const prisma = new PrismaClient();
const prismaClient = prisma.$extends(prismaPgtypedPreparedQuery());

export type PrismaClient = typeof prismaClient;

Once you have generated your PreparedQuery with @pgtyped/cli, you can directly use it with the prisma client:

// post.repository.ts
import { PrismaClient } from './prisma-client';
import {
  findAllPostsRawQuery,
  IFindAllPostsRawQueryResult,
} from "./find-all-posts.sql";

class PostRepository {
  constructor(private readonly prisma: PrismaClient) {}

  findAllPosts(clientId: string): Promise<IFindAllPostsRawQueryResult[]> {
    return this.prisma.$protected(findAllPostsRawQuery).with({ clientId });
  }
}

Customization

The extension use a set of classes to bridge PgTyped with Prisma. Those classes are intentionally exposed from the package for customizations.

| Class name | Description | | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | PrismaDatabaseConnection | The database connection implementing the PgTyped IDatabaseConnection to run the query, this is the communication layer between pgtyped and prisma | | PrismaPreparedQueryRunner | The runner adding a thin layer around the PreparedQuery to be more fluent |

For example, let's imagine that you want to validate at runtime the query output result. You could use the following snippet:

// prisma-client.ts
import { PreparedQuery } from "@pgtyped/runtime";
import { ClassConstructor, plainToInstance } from "class-transformer";
import { validateOrReject } from "class-validator";
import {
  PrismaDatabaseConnection,
  PrismaPreparedQueryRunner,
} from "prisma-pgtyped-prepared-query";

async function castAs<T extends object, V extends object>(
  dto: ClassConstructor<T>,
  rows: readonly V[]
): Promise<T[]> {
  const instances = plainToInstance(dto, [...rows]);
  if (instances.length > 0) await validateOrReject(instances[0]);

  return instances;
}

const prisma = new PrismaClient().$extends((prisma) => {
  prisma.$extends({
    name: "prisma-pgtyped-validated-prepared-query",
    client: {
      $prepared<TInput, TOutput>(query: PreparedQuery<TInput, TOutput>) {
        const runner = new PrismaPreparedQueryRunner(
          new PrismaDatabaseConnection(prisma),
          query
        );

        return {
          with(params: TInput) {
            return runner.with(params);
          },
          as<T>(dto: ClassConstructor<T>) {
            return {
              with: (params: TInput): Promise<T[]> => {
                const rows = await this.with(params);
                return castAs(dto, rows);
              },
            };
          },
        };
      },
    },
  });
});

export type PrismaClient = typeof prisma;

// ---
// post.repository.ts
import { PrismaClient } from "./prisma-client";
import { findAllPostsRawQuery } from "./find-all-posts.sql";

class Post {
  @IsUUID()
  id!: string;
}

class PostRepository {
  constructor(private readonly prisma: PrismaClient) {}

  findAllPosts(clientId: string): Promise<Post[]> {
    return this.prisma
      .$prepared(findAllPostsRawQuery)
      .as(Post)
      .with({ clientId });
  }
}