All Projects β†’ notiz-dev β†’ nestjs-prisma-starter

notiz-dev / nestjs-prisma-starter

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

Programming Languages

typescript
32286 projects
Dockerfile
14818 projects
javascript
184084 projects - #8 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to nestjs-prisma-starter

Nestjs Prisma Starter
Starter template for NestJS 😻 includes GraphQL with Prisma Client, Passport-JWT authentication, Swagger Api and Docker
Stars: ✭ 547 (-50.59%)
Mutual labels:  bcrypt, passportjs, nestjs, prisma
prisma-nestjs-graphql
Generate object types, inputs, args, etc. from prisma schema file for usage with @nestjs/graphql module
Stars: ✭ 276 (-75.07%)
Mutual labels:  nestjs, prisma, nestjs-graphql
aws-nestjs-starter
Serverless, AWS, NestJS, GraphQL and DynamoDB starter
Stars: ✭ 200 (-81.93%)
Mutual labels:  nestjs, type-graphql, nestjs-graphql
nestjs-prisma-docker
Dockerizing a NestJS app with Prisma and PostgreSQL
Stars: ✭ 42 (-96.21%)
Mutual labels:  nestjs, prisma, prisma2
goprisma
A Go wrapper for prisma to turn databases into GraphQL APIs using Go.
Stars: ✭ 54 (-95.12%)
Mutual labels:  prisma, prisma-client, prisma2
nest-prisma-rest-api-boilerplate
Nest + Prisma + TypeScript | REST API Starter repository
Stars: ✭ 24 (-97.83%)
Mutual labels:  nestjs, prisma, prisma2
stack
πŸ₯­ nxpm-stack lets you generate a complete and opinionated full-stack application in a Nx Workspace, ready to extend and deploy!
Stars: ✭ 98 (-91.15%)
Mutual labels:  nestjs, prisma
gondor
Nestjs Framework, Prisma database layer w/ Angular and Apollo.
Stars: ✭ 14 (-98.74%)
Mutual labels:  nestjs, prisma
MERN-BUS-APP
This is a MFRP (My first Real Project) assigned to me during my internship at Cognizant. Made with MERN Stack technology.
Stars: ✭ 92 (-91.69%)
Mutual labels:  passportjs, passport-jwt
gql2sql
GraphQL to SQL service example
Stars: ✭ 31 (-97.2%)
Mutual labels:  prisma-client, prisma2
chanyeong
πŸ‘¨β€πŸ’» chanyeong's portfolio and blog webpage
Stars: ✭ 39 (-96.48%)
Mutual labels:  passportjs, nestjs
nestjs-graphql-gateway
Apollo Federation support for NextJS GraphQL module. Note: There is support for federation in the official package now so this project is deprecated
Stars: ✭ 13 (-98.83%)
Mutual labels:  nestjs, nestjs-graphql
blitz
⚑️The Fullstack React Framework β€” built on Next.js
Stars: ✭ 11,558 (+944.08%)
Mutual labels:  prisma, prisma2
nestjs-graphql-serverless
Boilerplate for using NestJS with GraphQL (Code-First) on serverless environment (AWS Lambda)
Stars: ✭ 64 (-94.22%)
Mutual labels:  nestjs, nestjs-graphql
database-schema-examples
Database Schema Examples we strive to support in Prisma
Stars: ✭ 94 (-91.51%)
Mutual labels:  prisma, prisma2
fullstack-ts-boilerplate
Full-stack boilerplate in TS using modern technology
Stars: ✭ 25 (-97.74%)
Mutual labels:  nestjs, prisma
matnbaz
πŸ“š The source-code for matnbaz.net. A monorepo containing the back-end (NestJS/Prisma/Apollo), front-end (Next.js/Apollo) and some tooling.
Stars: ✭ 481 (-56.55%)
Mutual labels:  nestjs, prisma
nestjs-hybrid-auth
Open source social sign in NestJS. NestJS HybridAuth works with various identities providers such as Facebook, Twitter, Google and many more. It use passport authentication under the hood.
Stars: ✭ 36 (-96.75%)
Mutual labels:  passportjs, nestjs
typegraphql-nestjs
TypeGraphQL integration with NestJS
Stars: ✭ 117 (-89.43%)
Mutual labels:  nestjs, type-graphql
prisma-json-schema-generator
A generator for Prisma 2 to generate a valid JSON Schema (v7)
Stars: ✭ 145 (-86.9%)
Mutual labels:  prisma, prisma2

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 v8 v2 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 i -g @nestjs/cli

Install the dependencies for the Nest application:

npm 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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].