{"id":13406311,"url":"https://github.com/notiz-dev/nestjs-prisma-starter","last_synced_at":"2025-05-15T01:08:15.583Z","repository":{"id":37499493,"uuid":"160067449","full_name":"notiz-dev/nestjs-prisma-starter","owner":"notiz-dev","description":"Starter template for NestJS 😻 includes GraphQL with Prisma Client, Passport-JWT authentication, Swagger Api and Docker","archived":false,"fork":false,"pushed_at":"2024-07-08T07:07:30.000Z","size":3342,"stargazers_count":2451,"open_issues_count":13,"forks_count":351,"subscribers_count":36,"default_branch":"main","last_synced_at":"2025-05-04T03:34:39.247Z","etag":null,"topics":["bcrypt","code-first","graphql","nestjs","passport-jwt","passportjs","prisma"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/notiz-dev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"notiz-dev","patreon":"notiz_dev"}},"created_at":"2018-12-02T16:35:28.000Z","updated_at":"2025-05-03T18:59:35.000Z","dependencies_parsed_at":"2024-09-20T16:06:26.944Z","dependency_job_id":"0b69e495-ab09-4f13-bb84-556f8d39ce02","html_url":"https://github.com/notiz-dev/nestjs-prisma-starter","commit_stats":null,"previous_names":["fivethree-team/nestjs-prisma-client-example","fivethree-team/nestjs-prisma-client-starter"],"tags_count":0,"template":true,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/notiz-dev%2Fnestjs-prisma-starter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/notiz-dev%2Fnestjs-prisma-starter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/notiz-dev%2Fnestjs-prisma-starter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/notiz-dev%2Fnestjs-prisma-starter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/notiz-dev","download_url":"https://codeload.github.com/notiz-dev/nestjs-prisma-starter/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254254042,"owners_count":22039792,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bcrypt","code-first","graphql","nestjs","passport-jwt","passportjs","prisma"],"created_at":"2024-07-30T19:02:26.868Z","updated_at":"2025-05-15T01:08:10.570Z","avatar_url":"https://github.com/notiz-dev.png","language":"TypeScript","funding_links":["https://github.com/sponsors/notiz-dev","https://patreon.com/notiz_dev"],"categories":["TypeScript","Resources"],"sub_categories":[],"readme":"# Instructions\n\nStarter template for 😻 [NestJS](https://nestjs.com/) and [Prisma](https://www.prisma.io/).\n\n\u003e Checkout [NestJS Prisma Schematics](https://github.com/marcjulian/nestjs-prisma) to automatically add Prisma support to your Nest application.\n\n## Version\n\n| Branch                                                                                                       |  Nest | Prisma                                               |  Graphql                                                              |\n| ------------------------------------------------------------------------------------------------------------ | ----- | ---------------------------------------------------- | --------------------------------------------------------------------- |\n| main                                                                                                       | v9    | [v4](https://github.com/prisma/prisma)         | [Code-first](https://docs.nestjs.com/graphql/quick-start#code-first)  |\n| [nest-8-prisma-3](https://github.com/fivethree-team/nestjs-prisma-starter/tree/nest-8-prisma-3)                                                                                                       | v8    | [v3](https://github.com/prisma/prisma)         | [Code-first](https://docs.nestjs.com/graphql/quick-start#code-first)  |\n| [nest-7](https://github.com/fivethree-team/nestjs-prisma-starter/tree/nest-7)                                                                                                       | v7    | [v2](https://github.com/prisma/prisma2)         | [Code-first](https://docs.nestjs.com/graphql/quick-start#code-first)  |\n| [nest-6-prisma2-code-first](https://github.com/fivethree-team/nestjs-prisma-starter/tree/nest-6-prisma2-code-first) | v6    | [v2-preview](https://github.com/prisma/prisma2) | [Code-first](https://github.com/19majkel94/type-graphql)              |\n| [nest-6-code-first](https://github.com/fivethree-team/nestjs-prisma-starter/tree/nest-6-code-first)         | v6    | [v1](https://github.com/prisma/prisma)               | [Code-first](https://github.com/19majkel94/type-graphql)              |\n| [nest-6-sdl-first](https://github.com/fivethree-team/nestjs-prisma-starter/tree/nest-6-sdl-first)                                                                                        | v6    | [v1](https://github.com/prisma/prisma)               | [SDL First](https://docs.nestjs.com/graphql/quick-start#schema-first) |\n| [nest-5](https://github.com/fivethree-team/nestjs-prisma-starter/tree/nest-5)                     | v5    | [v1](https://github.com/prisma/prisma)               | [SDL First](https://docs.nestjs.com/graphql/quick-start#schema-first) |\n\n## Features\n\n- GraphQL w/ [playground](https://github.com/prisma/graphql-playground)\n- Code-First w/ [decorators](https://docs.nestjs.com/graphql/quick-start#code-first)\n- [Prisma](https://www.prisma.io/) for database modelling, migration and type-safe access (Postgres, MySQL \u0026 MongoDB)\n- 🔐 JWT authentication w/ [passport-jwt](https://github.com/mikenicholson/passport-jwt)\n- REST API docs w/ [Swagger](https://swagger.io/)\n\n## Overview\n\n- [Instructions](#instructions)\n  - [Features](#features)\n  - [Overview](#overview)\n  - [Prisma Setup](#prisma-setup)\n    - [1. Install Dependencies](#1-install-dependencies)\n    - [2. PostgreSQL with Docker](#2-PostgreSQL-with-docker)\n    - [3. Prisma: Prisma Migrate](#3-prisma-prisma-migrate)\n    - [4. Prisma: Prisma Client JS](#4-prisma-client-js)\n    - [5. Seed the database data with this script](#5-seed-the-database-data-with-this-script)\n    - [6. Start NestJS Server](#6-start-nestjs-server)\n  - [GraphQL Playground](#graphql-playground)\n  - [Rest Api](#rest-api)\n  - [Docker](#docker)\n  - [Schema Development](#schema-development)\n  - [NestJS - Api Schema](#nestjs---api-schema)\n    - [Resolver](#resolver)\n  - [GraphQL Client](#graphql-client)\n    - [Angular](#angular)\n      - [Setup](#setup)\n      - [Queries](#queries)\n      - [Mutations](#mutations)\n      - [Subscriptions](#subscriptions)\n      - [Authentication](#authentication)\n\n## Prisma Setup\n\n### 1. Install Dependencies\n\nInstall [Nestjs CLI](https://docs.nestjs.com/cli/usages) to start and [generate CRUD resources](https://trilon.io/blog/introducing-cli-generators-crud-api-in-1-minute)\n\n```bash\n# npm\nnpm i -g @nestjs/cli\n# yarn\nyarn add -g @nestjs/cli\n```\n\nInstall the dependencies for the Nest application:\n\n```bash\n# npm\nnpm install\n# yarn\nyarn install\n```\n\n### 2. PostgreSQL with Docker\n\nSetup a development PostgreSQL with Docker. Copy [.env.example](./.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.\n\nStart the PostgreSQL database\n\n```bash\ndocker-compose -f docker-compose.db.yml up -d\n# or\nnpm run docker:db\n```\n\n### 3. Prisma Migrate\n\n[Prisma Migrate](https://github.com/prisma/prisma2/tree/master/docs/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](./.env) file.\n\nUse Prisma Migrate in your [development environment](https://www.prisma.io/blog/prisma-migrate-preview-b5eno5g08d0b#evolving-the-schema-in-development) to\n\n1. Creates `migration.sql` file\n2. Updates Database Schema\n3. Generates Prisma Client\n\n```bash\nnpx prisma migrate dev\n# or\nnpm run migrate:dev\n```\n\nIf you like to customize your `migration.sql` file run the following command. After making your customizations run `npx prisma migrate dev` to apply it.\n\n```bash\nnpx prisma migrate dev --create-only\n# or\nnpm run migrate:dev:create\n```\n\nIf you are happy with your database changes you want to deploy those changes to your [production database](https://www.prisma.io/blog/prisma-migrate-preview-b5eno5g08d0b#applying-migrations-in-production-and-other-environments). Use `prisma migrate deploy` to apply all pending migrations, can also be used in CI/CD pipelines as it works without prompts.\n\n```bash\nnpx prisma migrate deploy\n# or\nnpm run migrate:deploy\n```\n\n### 4. Prisma: Prisma Client JS\n\n[Prisma Client JS](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/api) is a type-safe database client auto-generated based on the data model.\n\nGenerate Prisma Client JS by running\n\n\u003e **Note**: Every time you update [schema.prisma](prisma/schema.prisma) re-generate Prisma Client JS\n\n```bash\nnpx prisma generate\n# or\nnpm run prisma:generate\n```\n\n### 5. Seed the database data with this script\n\nExecute the script with this command:\n\n```bash\nnpm run seed\n```\n\n### 6. Start NestJS Server\n\nRun Nest Server in Development mode:\n\n```bash\nnpm run start\n\n# watch mode\nnpm run start:dev\n```\n\nRun Nest Server in Production mode:\n\n```bash\nnpm run start:prod\n```\n\nGraphQL Playground for the NestJS Server is available here: http://localhost:3000/graphql\n\n**[⬆ back to top](#overview)**\n\n## GraphQL Playground\n\nOpen up the [example GraphQL queries](graphql/auth.graphql) 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 `accessToken`as followed to **HTTP HEADERS** in the playground and replace `YOURTOKEN` here:\n\n```json\n{\n  \"Authorization\": \"Bearer YOURTOKEN\"\n}\n```\n\n## Rest Api\n\n[RESTful API](http://localhost:3000/api) documentation available with Swagger.\n\n## Docker\n\nNest server is a Node.js application and it is easily [dockerized](https://nodejs.org/de/docs/guides/nodejs-docker-webapp/).\n\nSee the [Dockerfile](./Dockerfile) on how to build a Docker image of your Nest server.\n\nNow to build a Docker image of your own Nest server simply run:\n\n```bash\n# give your docker image a name\ndocker build -t \u003cyour username\u003e/nest-prisma-server .\n# for example\ndocker build -t nest-prisma-server .\n```\n\nAfter Docker build your docker image you are ready to start up a docker container running the nest server:\n\n```bash\ndocker run -d -t -p 3000:3000 --env-file .env nest-prisma-server\n```\n\nNow open up [localhost:3000](http://localhost:3000) to verify that your nest server is running.\n\nWhen you run your NestJS application in a Docker container update your [.env](.env) file\n\n```diff\n- DB_HOST=localhost\n# replace with name of the database container\n+ DB_HOST=postgres\n\n# Prisma database connection\n+ DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${DB_HOST}:${DB_PORT}/${POSTGRES_DB}?schema=${DB_SCHEMA}\u0026sslmode=prefer\n```\n\nIf `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:\n\n```bash\n(node:19) UnhandledPromiseRejectionWarning: Error: error: Environment variable not found: DATABASE_URL.\n  --\u003e  schema.prisma:3\n   |\n 2 |   provider = \"postgresql\"\n 3 |   url      = env(\"DATABASE_URL\")\n```\n\n### Docker Compose\n\nYou can also setup a the database and Nest application with the docker-compose\n\n```bash\n# building new NestJS docker image\ndocker-compose build\n# or\nnpm run docker:build\n\n# start docker-compose\ndocker-compose up -d\n# or\nnpm run docker\n```\n\n## Schema Development\n\nUpdate the Prisma schema `prisma/schema.prisma` and after that run the following two commands:\n\n```bash\nnpx prisma generate\n# or in watch mode\nnpx prisma generate --watch\n# or\nnpm run prisma:generate\nnpm run prisma:generate:watch\n```\n\n**[⬆ back to top](#overview)**\n\n## NestJS - Api Schema\n\nThe [schema.graphql](./src/schema.graphql) is generated with [code first approach](https://docs.nestjs.com/graphql/quick-start#code-first) from the models, resolvers and input classes.\n\nYou can use [class-validator](https://docs.nestjs.com/techniques/validation) to validate your inputs and arguments.\n\n### Resolver\n\nTo implement the new query, a new resolver function needs to be added to `users.resolver.ts`.\n\n```ts\n@Query(returns =\u003e User)\nasync getUser(@Args() args): Promise\u003cUser\u003e {\n  return await this.prisma.client.user(args);\n}\n```\n\nRestart the NestJS server and this time the Query to fetch a `user` should work.\n\n**[⬆ back to top](#overview)**\n\n## GraphQL Client\n\nA GraphQL client is necessary to consume the GraphQL api provided by the NestJS Server.\n\nCheckout [Apollo](https://www.apollographql.com/) a popular GraphQL client which offers several clients for React, Angular, Vue.js, Native iOS, Native Android and more.\n\n### Angular\n\n#### Setup\n\nTo start using [Apollo Angular](https://www.apollographql.com/docs/angular/basics/setup.html) simply run in an Angular and Ionic project:\n\n```bash\nng add apollo-angular\n```\n\n`HttpLink` from apollo-angular requires the `HttpClient`. Therefore, you need to add the `HttpClientModule` to the `AppModule`:\n\n```ts\nimports: [BrowserModule,\n    HttpClientModule,\n    ...,\n    GraphQLModule],\n```\n\nYou can also add the `GraphQLModule` in the `AppModule` to make `Apollo` available in your Angular App.\n\nYou need to set the URL to the NestJS GraphQL Api. Open the file `src/app/graphql.module.ts` and update `uri`:\n\n```ts\nconst uri = 'http://localhost:3000/graphql';\n```\n\nTo use Apollo-Angular you can inject `private apollo: Apollo` into the constructor of a page, component or service.\n\n**[⬆ back to top](#overview)**\n\n#### Queries\n\nTo execute a query you can use:\n\n```ts\nthis.apollo.query({query: YOUR_QUERY});\n\n# or\n\nthis.apollo.watchQuery({\n  query: YOUR_QUERY\n}).valueChanges;\n```\n\nHere is an example how to fetch your profile from the NestJS GraphQL Api:\n\n```ts\nconst CurrentUserProfile = gql`\n  query CurrentUserProfile {\n    me {\n      id\n      email\n      name\n    }\n  }\n`;\n\n@Component({\n  selector: 'app-home',\n  templateUrl: 'home.page.html',\n  styleUrls: ['home.page.scss'],\n})\nexport class HomePage implements OnInit {\n  data: Observable\u003cany\u003e;\n\n  constructor(private apollo: Apollo) {}\n\n  ngOnInit() {\n    this.data = this.apollo.watchQuery({\n      query: CurrentUserProfile,\n    }).valueChanges;\n  }\n}\n```\n\nUse the `AsyncPipe` and [SelectPipe](https://www.apollographql.com/docs/angular/basics/queries.html#select-pipe) to unwrap the data Observable in the template:\n\n```html\n\u003cdiv *ngIf=\"data | async | select: 'me' as me\"\u003e\n  \u003cp\u003eMe id: {{me.id}}\u003c/p\u003e\n  \u003cp\u003eMe email: {{me.email}}\u003c/p\u003e\n  \u003cp\u003eMe name: {{me.name}}\u003c/p\u003e\n\u003c/div\u003e\n```\n\nOr unwrap the data using [RxJs](https://www.apollographql.com/docs/angular/basics/queries.html#rxjs).\n\nThis will end up in an `GraphQL error` because `Me` is protected by an `@UseGuards(GqlAuthGuard)` and requires an `Bearer TOKEN`.\nPlease refer to the [Authentication](#authentication) section.\n\n**[⬆ back to top](#overview)**\n\n#### Mutations\n\nTo execute a mutation you can use:\n\n```ts\nthis.apollo.mutate({\n  mutation: YOUR_MUTATION,\n});\n```\n\nHere is an example how to login into your profile using the `login` Mutation:\n\n```ts\nconst Login = gql`\n  mutation Login {\n    login(email: \"test@example.com\", password: \"pizzaHawaii\") {\n      token\n      user {\n        id\n        email\n        name\n      }\n    }\n  }\n`;\n\n@Component({\n  selector: 'app-home',\n  templateUrl: 'home.page.html',\n  styleUrls: ['home.page.scss'],\n})\nexport class HomePage implements OnInit {\n  data: Observable\u003cany\u003e;\n\n  constructor(private apollo: Apollo) {}\n\n  ngOnInit() {\n    this.data = this.apollo.mutate({\n      mutation: Login,\n    });\n  }\n}\n```\n\n**[⬆ back to top](#overview)**\n\n#### Subscriptions\n\nTo execute a subscription you can use:\n\n```ts\nthis.apollo.subscribe({\n  query: YOUR_SUBSCRIPTION_QUERY,\n});\n```\n\n**[⬆ back to top](#overview)**\n\n#### Authentication\n\nTo authenticate your requests you have to add your `TOKEN` you receive on `signup` and `login` [mutation](#mutations) to each request which is protected by the `@UseGuards(GqlAuthGuard)`.\n\nBecause the apollo client is using `HttpClient` under the hood you are able to simply use an `Interceptor` to add your token to the requests.\n\nCreate the following class:\n\n```ts\nimport { Injectable } from '@angular/core';\nimport {\n  HttpEvent,\n  HttpInterceptor,\n  HttpHandler,\n  HttpRequest,\n} from '@angular/common/http';\nimport { Observable } from 'rxjs';\n\n@Injectable()\nexport class TokenInterceptor implements HttpInterceptor {\n  constructor() {}\n\n  intercept(\n    req: HttpRequest\u003cany\u003e,\n    next: HttpHandler\n  ): Observable\u003cHttpEvent\u003cany\u003e\u003e {\n    const token = 'YOUR_TOKEN'; // get from local storage\n    if (token !== undefined) {\n      req = req.clone({\n        setHeaders: {\n          Authorization: `Bearer ${token}`,\n        },\n      });\n    }\n\n    return next.handle(req);\n  }\n}\n```\n\nAdd the Interceptor to the `AppModule` providers like this:\n\n```ts\nproviders: [\n    ...\n    { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },\n    ...\n  ]\n```\n\nAfter you configured the Interceptor and retrieved the `TOKEN` from storage your request will succeed on resolvers with `@UseGuards(GqlAuthGuard)`.\n\n**[⬆ back to top](#overview)**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnotiz-dev%2Fnestjs-prisma-starter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnotiz-dev%2Fnestjs-prisma-starter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnotiz-dev%2Fnestjs-prisma-starter/lists"}