@prisma/client#PrismaClient TypeScript Examples

The following examples show how to use @prisma/client#PrismaClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: clean.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async function getTypes(prisma: PrismaClient): Promise<string[]> {
  const results: Array<{
    typname: string;
  }> = await prisma.$queryRaw`
 SELECT t.typname
 FROM pg_type t 
 JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
 WHERE n.nspname = 'public';
 `;
  return results.map((result) => result.typname);
}
Example #2
Source File: TodoDatabaseRepository.test.ts    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
describe("TodoDatabaseRepository", () => {
  let todos: Todos;
  let todoLists: TodoLists;
  let prisma: PrismaClient;

  beforeAll(() => configureTestingDatabaseEnvironment());

  beforeEach(async () => {
    await prepareDatabase();

    prisma = new PrismaClient();
    todos = new TodoDatabaseRepository(prisma);
    todoLists = new TodoListDatabaseRepository(prisma);
  });

  afterEach(() => prisma.$disconnect());

  it("persists and retrieves todos", async () => {
    const theTodoId = "eb7531dd-0e2b-47b6-9bca-47182995f3ab";
    const todoList = aTodoList().build();
    await todoLists.save(todoList);

    // Persist todos
    let todo = aTodo().withId(theTodoId).ofTodoList(todoList.id).build();
    await todos.save(todo);
    expect(await todos.ofId(theTodoId)).toEqual(todo);

    // Updates todos
    todo = updateCompletion(todo, true);
    await todos.save(todo);
    expect(await todos.ofId(theTodoId)).toEqual(todo);

    // Removes todos
    await todos.remove(theTodoId);
    await expect(todos.ofId(theTodoId)).rejects.toThrow(
      new Error("No Todo found")
    );
  });
});
Example #3
Source File: adapter.ts    From prisma-adapter with Apache License 2.0 6 votes vote down vote up
/**
   * @param option It should be PrismaClientOptions or PrismaClient.
   * You should later call open() to activate it.
   */
  constructor(option?: Prisma.PrismaClientOptions | PrismaClient) {
    if (option instanceof PrismaClient) {
      this.#prisma = option;
    } else {
      this.#option = option;
    }
  }
Example #4
Source File: seed.ts    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
async function doSeed() {
  const prisma = new PrismaClient();

  await prisma.account.create({
    data: {
      id: "051cef90-ee3a-4046-a9dd-f5cdc303d073",
      email: "[email protected]",
      hash: "$2b$10$5Z4G6eRXFw2KqEArn1eXNOlNGOZXQXcyZ2IkXYLcDhWNKfqyVJQkS", // Password is azertyuiop :)
      verified: true,
    },
  });
}
Example #5
Source File: generate-graphql-schema.ts    From amplication with Apache License 2.0 6 votes vote down vote up
export default async function generateGraphQLSchema(): Promise<void> {
  // Override PrismaClient $connect to prevent connections to the database
  PrismaClient.prototype.$connect = async function() {
    return;
  };
  // Use the side effect of initializing the nest application for generating
  // the Nest.js schema
  const app = await NestFactory.create(AppModule);
  await app.init();
}
Example #6
Source File: adapter.ts    From prisma-adapter with Apache License 2.0 6 votes vote down vote up
#open = async (): Promise<void> => {
    if (!this.#option) {
      this.#option = {};
    }
    if (!this.#prisma) {
      this.#prisma = new PrismaClient(this.#option);
    }
    await this.#prisma.$connect();
  };
Example #7
Source File: clean.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async function getTypes(prisma: PrismaClient): Promise<string[]> {
  const results: Array<{
    typname: string;
  }> = await prisma.$queryRaw`
SELECT t.typname
FROM pg_type t 
JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
WHERE n.nspname = 'public';
`;
  return results.map(result => result.typname);
}
Example #8
Source File: index.ts    From fullstack-starterkit with MIT License 6 votes vote down vote up
class Prisma extends PrismaClient {
  private static instance: Prisma;

  private constructor() {
    super();
  }

  static getInstance(): Prisma {
    if (!Prisma.instance) {
      Prisma.instance = new Prisma();
    }

    return Prisma.instance;
  }
}
Example #9
Source File: clean.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async function clean() {
  console.info('Dropping all tables in the database...');
  const prisma = new PrismaClient();
  const tables = await getTables(prisma);
  const types = await getTypes(prisma);
  await dropTables(prisma, tables);
  await dropTypes(prisma, types);
  console.info('Cleaned database successfully');
  await prisma.$disconnect();
}
Example #10
Source File: user.resolver.ts    From prisma-nestjs-graphql with MIT License 6 votes vote down vote up
prisma = new PrismaClient({
  errorFormat: 'colorless',
  log: [
    {
      emit: 'event',
      level: 'query',
    },
  ],
})
Example #11
Source File: utils.ts    From frames with Mozilla Public License 2.0 6 votes vote down vote up
prisma = global.prisma || new PrismaClient()
Example #12
Source File: Database.ts    From Mandroc with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Connects to the database.
   */
  static connect() {
    const prisma = new PrismaClient({
      log: [
        {
          emit: "event",
          level: "info"
        },
        {
          emit: "event",
          level: "error"
        }
      ]
    });

    prisma.$on("info", ({ message }) => this.LOGGER.debug(message));
    prisma.$on("error", ({ message }) => this.LOGGER.error(message));

    const enabledMiddleware = config.get<Middleware[]>("database.middleware", { envType: "array" })
    if (enabledMiddleware.length) {
      Database.addMiddleware(prisma, enabledMiddleware);
    }

    Database.PRISMA = prisma;
  }
Example #13
Source File: prisma.service.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
constructor(readonly config: ApiConfigService) {
    super({
      datasources: {
        db: {
          url: config.dbPoolUrl,
        },
      },
    });
    this.readClient = new PrismaClient({
      datasources: { db: { url: config.readDbPoolUrl } },
    });
  }
Example #14
Source File: seed.template.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async function seed(bcryptSalt: Salt) {
  console.info("Seeding database...");

  const client = new PrismaClient();
  const data = DATA;
  await client.user.upsert({
    where: { username: data.username },
    update: {},
    create: data,
  });
  void client.$disconnect();

  console.info("Seeding database with custom seed...");
  customSeed();

  console.info("Seeded database successfully");
}
Example #15
Source File: main.ts    From ts-oauth2-server with MIT License 5 votes vote down vote up
async function bootstrap() {
  const prisma = new PrismaClient();
  const authorizationServer = new AuthorizationServer(
    new AuthCodeRepository(prisma.oAuthAuthCode),
    new ClientRepository(prisma.oAuthClient),
    new TokenRepository(prisma.oAuthToken),
    new ScopeRepository(prisma.oAuthScope),
    new UserRepository(prisma.user),
    new JwtService(process.env.OAUTH_CODES_SECRET!),
  );
  authorizationServer.enableGrantTypes(
    ["authorization_code", new DateInterval("15m")],
    ["client_credentials", new DateInterval("1d")],
    "refresh_token",
    "password",
    "implicit",
  );

  const fastify = Fastify({ logger: true });

  fastify.get("/authorize", async (req: FastifyRequest, res: FastifyReply) => {
    try {
      // Validate the HTTP request and return an AuthorizationRequest object.
      const authRequest = await authorizationServer.validateAuthorizationRequest(requestFromFastify(req));

      // The auth request object can be serialized and saved into a user's session.
      // You will probably want to redirect the user at this point to a login endpoint.

      // Once the user has logged in set the user on the AuthorizationRequest
      console.log("Once the user has logged in set the user on the AuthorizationRequest");
      authRequest.user = { id: "abc", email: "[email protected]" };

      // At this point you should redirect the user to an authorization page.
      // This form will ask the user to approve the client and the scopes requested.

      // Once the user has approved or denied the client update the status
      // (true = approved, false = denied)
      authRequest.isAuthorizationApproved = true;

      // Return the HTTP redirect response
      const oauthResponse = await authorizationServer.completeAuthorizationRequest(authRequest);
      return handleFastifyReply(res, oauthResponse);
    } catch (e) {
      handleFastifyError(e, res);
    }
  });

  fastify.post("/token", async (req: FastifyRequest, res: FastifyReply) => {
    const request = requestFromFastify(req);
    try {
      const oauthResponse = await authorizationServer.respondToAccessTokenRequest(request);
      return handleFastifyReply(res, oauthResponse);
    } catch (e) {
      handleFastifyError(e, res);
      return;
    }
  });

  fastify.get("/", (_req: FastifyRequest, res: FastifyReply) => {
    res.send({
      success: true,
      GET: ["/authorize"],
      POST: ["/token"],
    });
  });

  await fastify.listen(3000);

  console.log("app is listening on localhost:3000");
}
Example #16
Source File: prisma.ts    From website with MIT License 5 votes vote down vote up
prisma: PrismaClient
Example #17
Source File: prisma.service.ts    From ironfish-api with Mozilla Public License 2.0 5 votes vote down vote up
private readonly readClient: PrismaClient;
Example #18
Source File: prisma.ts    From ledokku with MIT License 5 votes vote down vote up
prisma = new PrismaClient()
Example #19
Source File: adapter.ts    From prisma-adapter with Apache License 2.0 5 votes vote down vote up
static async newAdapter(
    option?: Prisma.PrismaClientOptions | PrismaClient
  ): Promise<PrismaAdapter> {
    const a = new PrismaAdapter(option);
    await a.#open();

    return a;
  }
Example #20
Source File: __helpers.ts    From tutorial with MIT License 5 votes vote down vote up
function prismaTestContext() {
  const prismaBinary = join(__dirname, '..', 'node_modules', '.bin', 'prisma')
  let schema = ''
  let databaseUrl = ''
  let prismaClient: null | PrismaClient = null

  return {
    async before() {
      // Generate a unique schema identifier for this test context
      schema = `test_${nanoid()}`
      // Generate the pg connection string for the test schema
      databaseUrl = `postgres://postgres:postgres@localhost:5432/testing?schema=${schema}`

      // Set the required environment variable to contain the connection string
      // to our database test schema
      process.env.DATABASE_URL = databaseUrl

      // Run the migrations to ensure our schema has the required structure
      execSync(`${prismaBinary} migrate up --create-db --experimental`, {
        env: {
          ...process.env,
          DATABASE_URL: databaseUrl,
        },
      })

      // Construct a new Prisma Client connected to the generated Postgres schema
      prismaClient = new PrismaClient()

      return prismaClient
    },
    async after() {
      // Drop the schema after the tests have completed
      const client = new Client({
        connectionString: databaseUrl,
      })
      await client.connect()
      await client.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`)
      await client.end()

      // Release the Prisma Client connection
      await prismaClient?.$disconnect()
    },
  }
}
Example #21
Source File: prisma.ts    From ultimate-saas-ts with MIT License 5 votes vote down vote up
prisma = global.prisma || new PrismaClient()
Example #22
Source File: main.ts    From ts-oauth2-server with MIT License 5 votes vote down vote up
async function bootstrap() {
  const prisma = new PrismaClient();
  const authorizationServer = new AuthorizationServer(
    new AuthCodeRepository(prisma.oAuthAuthCode),
    new ClientRepository(prisma.oAuthClient),
    new TokenRepository(prisma.oAuthToken),
    new ScopeRepository(prisma.oAuthScope),
    new UserRepository(prisma.user),
    new JwtService(process.env.OAUTH_CODES_SECRET!),
  );
  authorizationServer.enableGrantTypes(
    ["authorization_code", new DateInterval("15m")],
    ["client_credentials", new DateInterval("1d")],
    "refresh_token",
    "password",
    "implicit",
  );

  const app = Express();

  app.use(json());
  app.use(urlencoded({ extended: false }));

  app.get("/authorize", async (req: Express.Request, res: Express.Response) => {
    try {
      // Validate the HTTP request and return an AuthorizationRequest object.
      const authRequest = await authorizationServer.validateAuthorizationRequest(requestFromExpress(req));

      // The auth request object can be serialized and saved into a user's session.
      // You will probably want to redirect the user at this point to a login endpoint.

      // Once the user has logged in set the user on the AuthorizationRequest
      console.log("Once the user has logged in set the user on the AuthorizationRequest");
      authRequest.user = { id: "abc", email: "[email protected]" };

      // At this point you should redirect the user to an authorization page.
      // This form will ask the user to approve the client and the scopes requested.

      // Once the user has approved or denied the client update the status
      // (true = approved, false = denied)
      authRequest.isAuthorizationApproved = true;

      // Return the HTTP redirect response
      const oauthResponse = await authorizationServer.completeAuthorizationRequest(authRequest);
      return handleExpressResponse(res, oauthResponse);
    } catch (e) {
      handleExpressError(e, res);
    }
  });

  app.post("/token", async (req: Express.Request, res: Express.Response) => {
    try {
      const oauthResponse = await authorizationServer.respondToAccessTokenRequest(req);
      return handleExpressResponse(res, oauthResponse);
    } catch (e) {
      handleExpressError(e, res);
      return;
    }
  });

  app.get("/", (_: Express.Request, res: Express.Response) => {
    res.json({
      success: true,
      GET: ["/authorize"],
      POST: ["/token"],
    });
  });

  app.listen(3000);

  console.log("app is listening on localhost:3000");
}
Example #23
Source File: db.ts    From tutorial with MIT License 5 votes vote down vote up
db = new PrismaClient()
Example #24
Source File: client.ts    From telefunc with MIT License 5 votes vote down vote up
prisma = new PrismaClient()
Example #25
Source File: prisma.service.ts    From ironfish-api with Mozilla Public License 2.0 5 votes vote down vote up
@Injectable()
export class PrismaService
  extends PrismaClient
  implements OnModuleInit, OnModuleDestroy
{
  private readonly readClient: PrismaClient;

  constructor(readonly config: ApiConfigService) {
    super({
      datasources: {
        db: {
          url: config.dbPoolUrl,
        },
      },
    });
    this.readClient = new PrismaClient({
      datasources: { db: { url: config.readDbPoolUrl } },
    });
  }

  $queryRawUnsafe<T = unknown>(
    query: string,
    ...values: unknown[]
  ): PrismaPromise<T> {
    if (this.config.isProduction()) {
      return this.readClient.$queryRawUnsafe<T>(query, ...values);
    }
    return super.$queryRawUnsafe<T>(query, ...values);
  }

  async onModuleInit(): Promise<void> {
    await this.$connect();
    await this.readClient.$connect();
  }

  async onModuleDestroy(): Promise<void> {
    await this.$disconnect();
    await this.readClient.$disconnect();
  }
}
Example #26
Source File: adapter.ts    From prisma-adapter with Apache License 2.0 5 votes vote down vote up
#prisma: PrismaClient;
Example #27
Source File: client.ts    From next-crud with MIT License 5 votes vote down vote up
prisma = new PrismaClient()
Example #28
Source File: index.ts    From nlw-heat-node with MIT License 5 votes vote down vote up
prismaClient = new PrismaClient()
Example #29
Source File: context.ts    From mayoor with MIT License 5 votes vote down vote up
prisma = new PrismaClient({ log: ['query', 'info', 'warn'] })