Giter Site home page Giter Site logo

notiz-dev / nestjs-prisma-starter Goto Github PK

View Code? Open in Web Editor NEW
2.2K 37.0 315.0 3.26 MB

Starter template for NestJS 😻 includes GraphQL with Prisma Client, Passport-JWT authentication, Swagger Api and Docker

License: MIT License

TypeScript 96.69% Dockerfile 1.28% Shell 0.23% JavaScript 1.80%
nestjs prisma passportjs passport-jwt bcrypt code-first graphql

nestjs-prisma-starter's Introduction

Instructions

Starter template for 😻 NestJS and Prisma.

Checkout NestJS Prisma Schematics to automatically add Prisma support to your Nest application.

Version

Branch  Nest Prisma  Graphql
main v9 v4 Code-first
nest-8-prisma-3 v8 v3 Code-first
nest-7 v7 v2 Code-first
nest-6-prisma2-code-first v6 v2-preview Code-first
nest-6-code-first v6 v1 Code-first
nest-6-sdl-first v6 v1 SDL First
nest-5 v5 v1 SDL First

Features

Overview

Prisma Setup

1. Install Dependencies

Install Nestjs CLI to start and generate CRUD resources

# npm
npm i -g @nestjs/cli
# yarn
yarn add -g @nestjs/cli

Install the dependencies for the Nest application:

# npm
npm install
# yarn
yarn install

2. PostgreSQL with Docker

Setup a development PostgreSQL with Docker. Copy .env.example and rename to .env - cp .env.example .env - which sets the required environments for PostgreSQL such as POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB. Update the variables as you wish and select a strong password.

Start the PostgreSQL database

docker-compose -f docker-compose.db.yml up -d
# or
npm run docker:db

3. Prisma Migrate

Prisma Migrate is used to manage the schema and migration of the database. Prisma datasource requires an environment variable DATABASE_URL for the connection to the PostgreSQL database. Prisma reads the DATABASE_URL from the root .env file.

Use Prisma Migrate in your development environment to

  1. Creates migration.sql file
  2. Updates Database Schema
  3. Generates Prisma Client
npx prisma migrate dev
# or
npm run migrate:dev

If you like to customize your migration.sql file run the following command. After making your customizations run npx prisma migrate dev to apply it.

npx prisma migrate dev --create-only
# or
npm run migrate:dev:create

If you are happy with your database changes you want to deploy those changes to your production database. Use prisma migrate deploy to apply all pending migrations, can also be used in CI/CD pipelines as it works without prompts.

npx prisma migrate deploy
# or
npm run migrate:deploy

4. Prisma: Prisma Client JS

Prisma Client JS is a type-safe database client auto-generated based on the data model.

Generate Prisma Client JS by running

Note: Every time you update schema.prisma re-generate Prisma Client JS

npx prisma generate
# or
npm run prisma:generate

5. Seed the database data with this script

Execute the script with this command:

npm run seed

6. Start NestJS Server

Run Nest Server in Development mode:

npm run start

# watch mode
npm run start:dev

Run Nest Server in Production mode:

npm run start:prod

GraphQL Playground for the NestJS Server is available here: http://localhost:3000/graphql

⬆ back to top

GraphQL Playground

Open up the example GraphQL queries and copy them to the GraphQL Playground. Some queries and mutations are secured by an auth guard. You have to acquire a JWT token from signup or login. Add the accessTokenas followed to HTTP HEADERS in the playground and replace YOURTOKEN here:

{
  "Authorization": "Bearer YOURTOKEN"
}

Rest Api

RESTful API documentation available with Swagger.

Docker

Nest server is a Node.js application and it is easily dockerized.

See the Dockerfile on how to build a Docker image of your Nest server.

Now to build a Docker image of your own Nest server simply run:

# give your docker image a name
docker build -t <your username>/nest-prisma-server .
# for example
docker build -t nest-prisma-server .

After Docker build your docker image you are ready to start up a docker container running the nest server:

docker run -d -t -p 3000:3000 --env-file .env nest-prisma-server

Now open up localhost:3000 to verify that your nest server is running.

When you run your NestJS application in a Docker container update your .env file

- DB_HOST=localhost
# replace with name of the database container
+ DB_HOST=postgres

# Prisma database connection
+ DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${DB_HOST}:${DB_PORT}/${POSTGRES_DB}?schema=${DB_SCHEMA}&sslmode=prefer

If DATABASE_URL is missing in the root .env file, which is loaded into the Docker container, the NestJS application will exit with the following error:

(node:19) UnhandledPromiseRejectionWarning: Error: error: Environment variable not found: DATABASE_URL.
  -->  schema.prisma:3
   |
 2 |   provider = "postgresql"
 3 |   url      = env("DATABASE_URL")

Docker Compose

You can also setup a the database and Nest application with the docker-compose

# building new NestJS docker image
docker-compose build
# or
npm run docker:build

# start docker-compose
docker-compose up -d
# or
npm run docker

Schema Development

Update the Prisma schema prisma/schema.prisma and after that run the following two commands:

npx prisma generate
# or in watch mode
npx prisma generate --watch
# or
npm run prisma:generate
npm run prisma:generate:watch

⬆ back to top

NestJS - Api Schema

The schema.graphql is generated with code first approach from the models, resolvers and input classes.

You can use class-validator to validate your inputs and arguments.

Resolver

To implement the new query, a new resolver function needs to be added to users.resolver.ts.

@Query(returns => User)
async getUser(@Args() args): Promise<User> {
  return await this.prisma.client.user(args);
}

Restart the NestJS server and this time the Query to fetch a user should work.

⬆ back to top

GraphQL Client

A GraphQL client is necessary to consume the GraphQL api provided by the NestJS Server.

Checkout Apollo a popular GraphQL client which offers several clients for React, Angular, Vue.js, Native iOS, Native Android and more.

Angular

Setup

To start using Apollo Angular simply run in an Angular and Ionic project:

ng add apollo-angular

HttpLink from apollo-angular requires the HttpClient. Therefore, you need to add the HttpClientModule to the AppModule:

imports: [BrowserModule,
    HttpClientModule,
    ...,
    GraphQLModule],

You can also add the GraphQLModule in the AppModule to make Apollo available in your Angular App.

You need to set the URL to the NestJS GraphQL Api. Open the file src/app/graphql.module.ts and update uri:

const uri = 'http://localhost:3000/graphql';

To use Apollo-Angular you can inject private apollo: Apollo into the constructor of a page, component or service.

⬆ back to top

Queries

To execute a query you can use:

this.apollo.query({query: YOUR_QUERY});

# or

this.apollo.watchQuery({
  query: YOUR_QUERY
}).valueChanges;

Here is an example how to fetch your profile from the NestJS GraphQL Api:

const CurrentUserProfile = gql`
  query CurrentUserProfile {
    me {
      id
      email
      name
    }
  }
`;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
  data: Observable<any>;

  constructor(private apollo: Apollo) {}

  ngOnInit() {
    this.data = this.apollo.watchQuery({
      query: CurrentUserProfile,
    }).valueChanges;
  }
}

Use the AsyncPipe and SelectPipe to unwrap the data Observable in the template:

<div *ngIf="data | async | select: 'me' as me">
  <p>Me id: {{me.id}}</p>
  <p>Me email: {{me.email}}</p>
  <p>Me name: {{me.name}}</p>
</div>

Or unwrap the data using RxJs.

This will end up in an GraphQL error because Me is protected by an @UseGuards(GqlAuthGuard) and requires an Bearer TOKEN. Please refer to the Authentication section.

⬆ back to top

Mutations

To execute a mutation you can use:

this.apollo.mutate({
  mutation: YOUR_MUTATION,
});

Here is an example how to login into your profile using the login Mutation:

const Login = gql`
  mutation Login {
    login(email: "[email protected]", password: "pizzaHawaii") {
      token
      user {
        id
        email
        name
      }
    }
  }
`;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
  data: Observable<any>;

  constructor(private apollo: Apollo) {}

  ngOnInit() {
    this.data = this.apollo.mutate({
      mutation: Login,
    });
  }
}

⬆ back to top

Subscriptions

To execute a subscription you can use:

this.apollo.subscribe({
  query: YOUR_SUBSCRIPTION_QUERY,
});

⬆ back to top

Authentication

To authenticate your requests you have to add your TOKEN you receive on signup and login mutation to each request which is protected by the @UseGuards(GqlAuthGuard).

Because the apollo client is using HttpClient under the hood you are able to simply use an Interceptor to add your token to the requests.

Create the following class:

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const token = 'YOUR_TOKEN'; // get from local storage
    if (token !== undefined) {
      req = req.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`,
        },
      });
    }

    return next.handle(req);
  }
}

Add the Interceptor to the AppModule providers like this:

providers: [
    ...
    { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
    ...
  ]

After you configured the Interceptor and retrieved the TOKEN from storage your request will succeed on resolvers with @UseGuards(GqlAuthGuard).

⬆ back to top

nestjs-prisma-starter's People

Contributors

100lvlmaster avatar alan2207 avatar cha2hyun avatar chaunceyau avatar dependabot-support avatar dependabot[bot] avatar edbond88 avatar fabiofdsantos avatar haotan19 avatar hymair avatar leohxj avatar longtomjr avatar luluhoc avatar marcjulian avatar megazoll avatar mfakhrusy avatar oupsla avatar pluveto avatar renovate-bot avatar ruheni avatar sitogi avatar therocket avatar thomaschaaf avatar yuval-hazaz avatar zlwu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nestjs-prisma-starter's Issues

Missing arg fields in Schema

Hi,

I just used this repo first time and I found problems with arguments of queries not showing in grapqh playground

For example userPosts query has userId argument in resolver:

@ArgsType() export class UserIdArgs { @IsNotEmpty() userId: string; }

Generated queries in schema:

type Query { ... userPosts: [Post!]! }

So the playground would not execute the query. I am just learning GraphQL, so I was confused of the error.
"message": "Unknown argument "userId" on field "Query.userPosts".",

After adding @field() decorator, all works fine.

Solved:
@ArgsType() export class UserIdArgs { @Field() @IsNotEmpty() userId: string; }
Am I missing something? Thanks.

Unit tests coverage

Sorry for bothering again.

I was wondering if there is a way to make code coverage 100% with unit tests for this project. I don't know if this is possible but, it would be nice to have a good set of unit tests.

Do you think that this is a good idea? I cannot image how to test something like the classes in pagination.ts as they are only graphql type definitions.

But maybe, this is not a problem at all. I wish to discuss this with you.

Now, code coverage is getting very low score:

$ yarn test:cov
yarn run v1.22.5
$ jest --coverage
 PASS  src/controllers/app.controller.spec.ts
 PASS  src/common/scalars/date.scalar.spec.ts
 PASS  src/resolvers/app.resolver.spec.ts
 PASS  src/configs/config.spec.ts
---------------------------|---------|----------|---------|---------|-------------------
File                       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------------------|---------|----------|---------|---------|-------------------
All files                  |    8.94 |     2.44 |   14.63 |    8.12 |                   
 src                       |       0 |        0 |       0 |       0 |                   
  app.module.ts            |       0 |        0 |       0 |       0 | 1-41              
  main.ts                  |       0 |        0 |       0 |       0 | 1-38              
 src/common/order          |       0 |        0 |       0 |       0 |                   
  order-direction.ts       |       0 |        0 |       0 |       0 | 1-10              
  order.ts                 |       0 |      100 |       0 |       0 | 1-7               
 src/common/pagination     |       0 |      100 |       0 |       0 |                   
  page-info.model.ts       |       0 |      100 |     100 |       0 | 1-4               
  pagination.args.ts       |       0 |      100 |     100 |       0 | 1-4               
  pagination.ts            |       0 |      100 |       0 |       0 | 1-30              
 src/common/scalars        |   83.33 |       50 |      80 |      80 |                   
  date.scalar.ts           |   83.33 |       50 |      80 |      80 | 4,20              
 src/configs               |     100 |      100 |     100 |     100 |                   
  config.ts                |     100 |      100 |     100 |     100 |                   
 src/controllers           |     100 |      100 |     100 |     100 |                   
  app.controller.ts        |     100 |      100 |     100 |     100 |                   
 src/decorators            |       0 |      100 |       0 |       0 |                   
  user.decorator.ts        |       0 |      100 |       0 |       0 | 1-6               
 src/guards                |       0 |      100 |       0 |       0 |                   
  gql-auth.guard.ts        |       0 |      100 |       0 |       0 | 1-9               
 src/models                |       0 |        0 |       0 |       0 |                   
  auth.model.ts            |       0 |      100 |     100 |       0 | 1-6               
  model.model.ts           |       0 |      100 |       0 |       0 | 1-6               
  post.model.ts            |       0 |      100 |     100 |       0 | 1-6               
  token.model.ts           |       0 |      100 |     100 |       0 | 1-9               
  user.model.ts            |       0 |        0 |       0 |       0 | 1-28              
 src/models/args           |       0 |      100 |     100 |       0 |                   
  post-id.args.ts          |       0 |      100 |     100 |       0 | 1-7               
  user-id.args.ts          |       0 |      100 |     100 |       0 | 1-7               
 src/models/inputs         |       0 |        0 |       0 |       0 |                   
  post-order.input.ts      |       0 |        0 |       0 |       0 | 1-20              
 src/models/pagination     |       0 |      100 |     100 |       0 |                   
  post-connection.model.ts |       0 |      100 |     100 |       0 | 1-6               
 src/resolvers             |      80 |      100 |      50 |      75 |                   
  app.resolver.ts          |      80 |      100 |      50 |      75 | 5,9               
 src/resolvers/auth        |       0 |        0 |       0 |       0 |                   
  auth.module.ts           |       0 |      100 |       0 |       0 | 1-39              
  auth.resolver.ts         |       0 |      100 |       0 |       0 | 1-48              
  jwt.strategy.ts          |       0 |        0 |       0 |       0 | 2-26              
 src/resolvers/auth/dto    |       0 |      100 |     100 |       0 |                   
  login.input.ts           |       0 |      100 |     100 |       0 | 1-13              
  signup.input.ts          |       0 |      100 |     100 |       0 | 1-19              
 src/resolvers/post        |       0 |        0 |       0 |       0 |                   
  post.module.ts           |       0 |      100 |     100 |       0 | 1-8               
  post.resolver.ts         |       0 |        0 |       0 |       0 | 1-72              
 src/resolvers/user        |       0 |      100 |       0 |       0 |                   
  user.module.ts           |       0 |      100 |     100 |       0 | 1-10              
  user.resolver.ts         |       0 |      100 |       0 |       0 | 1-55              
 src/resolvers/user/dto    |       0 |      100 |     100 |       0 |                   
  change-password.input.ts |       0 |      100 |     100 |       0 | 1-14              
  update-user.input.ts     |       0 |      100 |     100 |       0 | 1-8               
 src/services              |       8 |        0 |   10.53 |    6.15 |                   
  app.service.ts           |     100 |      100 |     100 |     100 |                   
  auth.service.ts          |       0 |        0 |       0 |       0 | 1-100             
  password.service.ts      |       0 |        0 |       0 |       0 | 1-24              
  prisma.service.ts        |       0 |      100 |       0 |       0 | 1-15              
  user.service.ts          |       0 |        0 |       0 |       0 | 1-41              
---------------------------|---------|----------|---------|---------|-------------------

Test Suites: 4 passed, 4 total
Tests:       8 passed, 8 total
Snapshots:   0 total
Time:        4.629 s
Ran all test suites.
Done in 5.09s.

Logout feature

Why did you decide not to implement the Logout functionality?

Incompatible types

I'm using this example to build my own solution, but I stumbled into something that I'm not sure how to solve.

This is very much the same as the user.model.ts present in this example:

import { Field, ObjectType, registerEnumType } from "@nestjs/graphql"

export enum AccountStatus {
  Created = "Created",
  Verified = "Verified",
}

registerEnumType(AccountStatus, {
  name: "AccountStatus",
})

@ObjectType()
export class Account {
  @Field()
  public readonly slug: string

  @Field(() => AccountStatus)
  public status: AccountStatus
}

Then I have a service. In the return account I have a error message: Types of property 'status' are incompatible. because enums inside @prisma/client are defined as a const.

  public async create(input: AccountCreate): Promise<Account> {
    const account = await this.prismaService.account.create({
      data: {
        // whatever
      },
    })

    return account
  }

I can cast account to Account, but I prefer not to do that.

By default, Apollo's PubSub does not support production environments. Should we consider replacing it with Redis?

WARNING
The installSubscriptionHandlers configuration option has been removed from the latest version of Apollo server and will be soon deprecated in this package as well. By default, installSubscriptionHandlers will fallback to use the subscriptions-transport-ws (read more) but we strongly recommend using the graphql-ws(read more) library instead.

NOTE
PubSub is a class that exposes a simple publish and subscribe API. Read more about it here. Note that the Apollo docs warn that the default implementation is not suitable for production (read more here). Production apps should use a PubSub implementation backed by an external store (read more here).

nest docs

graphql-redis-subscriptions

Maybe I can get this done.

e2e tests: Undefined type error. Provide explicit type for the "user" of the "AuthResolver" class.

Bug

Steps to reproduce

Expected behaviour

e2e tests passed

Actual behaviour

$ jest --config ./test/jest-e2e.json
 FAIL  test/app.resolver.e2e-spec.ts
  ● AppResolver (e2e) › helloWorld (Query)

    Undefined type error. Make sure you are providing an explicit type for the "user" of the "AuthResolver" class.

      at TypeMetadataStorageHost.compileExternalFieldResolverMetadata (../node_modules/@nestjs/graphql/dist/schema-builder/storages/type-metadata.storage.js:256:23)
      at ../node_modules/@nestjs/graphql/dist/schema-builder/storages/type-metadata.storage.js:240:22
          at Array.forEach (<anonymous>)
      at TypeMetadataStorageHost.compileFieldResolverMetadata (../node_modules/@nestjs/graphql/dist/schema-builder/storages/type-metadata.storage.js:229:18)
      at TypeMetadataStorageHost.compile (../node_modules/@nestjs/graphql/dist/schema-builder/storages/type-metadata.storage.js:144:14)
      at GraphQLSchemaFactory.<anonymous> (../node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:38:57)
      at ../node_modules/@nestjs/graphql/node_modules/tslib/tslib.js:114:75
      at Object.__awaiter (../node_modules/@nestjs/graphql/node_modules/tslib/tslib.js:110:16)

  ● AppController (e2e) › /hello/:name (GET)

    Undefined type error. Make sure you are providing an explicit type for the "user" of the "AuthResolver" class.

[...]

How can I fix this? Thank you!

Rest api version

Hi, the example is using graphql, is threre an example showing how to integrate nestjs with prisma2 using rest api?

Getting Started: Error querying the database: db error: FATAL: role "prisma" does not exist

I am completely new to both NestJS and Prisma so forgive me if I am making a silly mistake. 🤦

I've run through the instructions a couple of times and can't seem to get past Step 3.

To reproduce:

git clone https://github.com/fivethree-team/nestjs-prisma-starter
cd nestjs-prisma-starter
npm install
cp example.env .env 
npm run docker:db
npm run migrate:dev

Which results in the following error: Error querying the database: db error: FATAL: role "prisma" does not exist

- error TS2307: Cannot find module '@apollo/gateway'

i got the following error

npm run start

[email protected] start
nest start

node_modules/@nestjs/graphql/dist/interfaces/gql-gateway-module-options.interface.d.ts:1:58 - error TS2307: Cannot find module '@apollo/gateway' or its corresponding type declarations.

1 import { GatewayConfig, ServiceEndpointDefinition } from '@apollo/gateway';
~~~~~~~~~~~~~~~~~
node_modules/@nestjs/graphql/dist/interfaces/gql-gateway-module-options.interface.d.ts:2:35 - error TS2307: Cannot find module '@apollo/gateway/src/datasources/types' or its corresponding type declarations.

2 import { GraphQLDataSource } from '@apollo/gateway/src/datasources/types';
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Found 2 error(s).

i run with :

npm version 7.11.2
node version 15.12.0

Feature Request: Exception Handling

This code involves 3 things: a. GraphQL support b. Nest JS c. Prisma All of them have their own built-in support for exceptions and errors.

Can we write the Exception handling together? I'd write the basic code and expect that someone among you help take the code to a 'production-ready" state?

Maintain frontend in same repo without sharing dependencies

Hi,

thanks a lot for this starter, really appreciate it!

I'm trying to put this starter together with same frontend project in the same repo using yarn workspaces.

My approach so far:

  • Move everything to apps/api/
  • Create package.json like this:
{
   "private": true,
   "name": "example-monorepo",
   "workspaces": ["apps/api"],
   "scripts": {}
}
  • Run yarn install
  • Run yarn workspace nestjs-prisma-client-starter start:dev

That works for the starter. However, for my existing project with frontend included already I'm experiencing several issues (e.g. nest-cli-plugins not working, VSCode configuration getting tricky, ...). I haven't really found out why (maybe the hoisting is problem...) and it is difficult to debug (for me).

I would assume having a frontend as well is kind of usual and I'm not the only one facing this problem ;-)

What is the standard way to approach this challenge?

I know, that Nestjs has some its own support for monorepos (https://docs.nestjs.com/cli/monorepo). However, this approach does not allow to have a different dependencies (package.json) etc. per app (which I would like to have to avoid dependency problems...).

Is there some middle ground between keeping everything in separate repos and completely sharing all dependencies, that is proven and well established in the community?

Docker compose up error "Could not find package.json"

Hey there!

I've been trying to run the project with docker by running: npm run docker or docker-compose -f docker-compose.yml up --build

And it gives me an error which I can't find a solution to. The error is:

> [email protected] start:prod
nest-api    | > node dist/main
nest-api    | 
nest-api    | /node_modules/flaschenpost/dist/readPackageJson.js:16
nest-api    |     throw new Error('Could not find package.json.');
nest-api    |     ^
nest-api    | 
nest-api    | Error: Could not find package.json.
nest-api    |     at readPackageJson (/node_modules/flaschenpost/dist/readPackageJson.js:16:11)
nest-api    |     at Object.flaschenpost.initialize (/node_modules/flaschenpost/dist/flaschenpost.js:23:36)
nest-api    |     at Object.<anonymous> (/node_modules/flaschenpost/dist/flaschenpost.js:111:14)
nest-api    |     at Module._compile (node:internal/modules/cjs/loader:1126:14)
nest-api    |     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
nest-api    |     at Module.load (node:internal/modules/cjs/loader:1004:32)
nest-api    |     at Function.Module._load (node:internal/modules/cjs/loader:839:12)
nest-api    |     at Module.require (node:internal/modules/cjs/loader:1028:19)
nest-api    |     at require (node:internal/modules/cjs/helpers:102:18)
nest-api    |     at Object.<anonymous> (/node_modules/node-poeditor/lib/workers/request/httprequest.js:4:16)
nest-api exited with code 1

Any idea what I could do to fix this? It seems that the package.json is in copied in the Dockerfile, but when running npm run start:prod it does not find it.

This line opens a new connection for every service that includes prisma.

https://github.com/fivethree-team/nestjs-prisma-starter/blob/c029a2a52ef3c9f21572629ac9b298a0d8c25594/src/services/prisma.service.ts#L12

I noticed at the start of the web server that it would take 5+ seconds and was taking longer and longer with every module I added to my project. It seems it tried to connect oninit for each service that uses this service. When I removed this line the project started under 1 second and Prisma has lazy loading connection that auto connects if no connection is established.

I see this in other docs and am wondering why its setup this way if it tries to front-load so many connections?

Vulnerabilities & npm audit fix

Executing npm install gives found 7344 vulnerabilities (7332 low, 12 moderate).

Any known constraint to avoid npm audit fix?

Question: When to invoke refreshToken() endpoint from the client?

I have a question relating to JWT, could you pl. answer?

There is a mutation named, refreshToken() which is exposed as an endpoint. In the documentation, there is no mention about when to make a call to this endpoint? Over there, it is just stated that send the token in the Authorization header.

Kindly make things clear by writing the generic code flow at client side. Is there any need to use a library like jwt-decode there?

MaxListenersExceededWarning

If you create more than 10 modules in the providers of which "PrismaService" is located, the error "Possible EventEmitter memory leak detected." The more modules are added, the more error instances are displayed. Is there a way to fix this?

Снимок экрана 2021-04-10 в 07 33 29
Снимок экрана 2021-04-10 в 07 32 27

Error
(node:15126) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 beforeExit listeners added to [process]. Use emitter.setMaxListeners() to increase limit (Use node --trace-warnings ... to show where the warning was created) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 beforeExit listeners added to [process]. Use emitter.setMaxListeners() to increase limit at _addListener (events.js:390:17) at process.addListener (events.js:406:10) at process.once (events.js:437:8) at hookProcess (/Users/Rikka/iMac/Projects/apps/nestGQLError2/node_modules/@prisma/client/runtime/index.js:27586:13) at initHooks (/Users/Rikka/iMac/Projects/apps/nestGQLError2/node_modules/@prisma/client/runtime/index.js:27609:9) at new NodeEngine (/Users/Rikka/iMac/Projects/apps/nestGQLError2/node_modules/@prisma/client/runtime/index.js:26911:7) at PrismaService.getEngine (/Users/Rikka/iMac/Projects/apps/nestGQLError2/node_modules/@prisma/client/runtime/index.js:34057:16) at new NewPrismaClient (/Users/Rikka/iMac/Projects/apps/nestGQLError2/node_modules/@prisma/client/runtime/index.js:34030:29) at new PrismaService (/Users/Rikka/iMac/Projects/apps/nestGQLError2/dist/services/prisma.service.js:17:9) at Injector.instantiateClass (/Users/Rikka/iMac/Projects/apps/nestGQLError2/node_modules/@nestjs/core/injector/injector.js:286:19)

Duplication between prisma schema and models

Hi!
First of all thanks for this starter. It is really awesome 😃

I've noticed that some of the code is duplicated between prisma schema definitions and nest js models.
In prisma.schema we have a User definition, which looks like below:

model User {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  email     String   @unique
  password  String
  firstname String?
  lastname  String?
  posts     Post[]
  role      Role
}

And also in user.model we define the same 'shape' but with typescript:

@ObjectType()
export class User extends BaseModel {
  email: string;
  firstname?: string;
  lastname?: string;
  role: Role;
  @HideField()
  password: string;
}

Why is that necessary? Can't we somehow generate schema from models, or other way around?

No such file or directory

When I am trying to run docker-compose up I get this error:

Step 4/10 : COPY ./prisma/schema.prisma ./
ERROR: Service 'nest-api' failed to build: COPY failed: stat /var/lib/docker/tmp/docker-builder161410517/prisma/schema.prisma: no such file or directory

I am using Docker in Mac. I have also tried the same with my RockPro64 server runs on Ubuntu 18.04. still having the same issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.