Skip to content

Commit

Permalink
Merge pull request #64 from belgattitude/auth-prisma
Browse files Browse the repository at this point in the history
Feat: example with next-auth and prisma
  • Loading branch information
belgattitude authored May 26, 2021
2 parents fafaef8 + 739d11a commit 754df64
Show file tree
Hide file tree
Showing 36 changed files with 1,563 additions and 52 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilly-bikes-deliver.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'web-app': minor
---

Add prisma and next-auth example
2 changes: 1 addition & 1 deletion .changeset/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"changelog": ["@changesets/changelog-github", { "repo": "belgattitude/nextjs-monorepo-example" }],
"commit": false,
"linked": [],
"access": "public",
"access": "private",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": [],
Expand Down
5 changes: 5 additions & 0 deletions .changeset/eleven-mugs-protect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@your-org/core-lib': minor
---

Add example asserts and typeguards
5 changes: 5 additions & 0 deletions .changeset/funny-suns-exist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@your-org/core-lib': minor
---

Add jest example for packages
5 changes: 4 additions & 1 deletion .eslintrc.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@
"assert": "readonly",
"Cypress": "readonly"
},
"rules": {},
"rules": {
"no-empty-function": "off",
"@typescript-eslint/no-empty-function": ["error",{"allow": ["private-constructors", "decoratedFunctions"]}]
},
"overrides": [
{
"files": [
Expand Down
5 changes: 5 additions & 0 deletions .github/workflows/ci-web-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ jobs:
run: |
yarn dedupe --check
#- name: Generate Prisma client
# working-directory: apps/web-app
# run: |
# yarn prisma generate

- name: Typecheck
working-directory: apps/web-app
run: |
Expand Down
8 changes: 5 additions & 3 deletions apps/blog-app/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ const { compilerOptions: baseTsConfig } = require('./tsconfig.json');
// Take the paths from tsconfig automatically from base tsconfig.json
// @link https://kulshekhar.github.io/ts-jest/docs/paths-mapping
const getTsConfigBasePaths = () => {
return pathsToModuleNameMapper(baseTsConfig.paths, {
prefix: '<rootDir>/',
});
return baseTsConfig.paths
? pathsToModuleNameMapper(baseTsConfig.paths, {
prefix: '<rootDir>/',
})
: {};
};

/** @typedef {import('ts-jest')} */
Expand Down
3 changes: 1 addition & 2 deletions apps/blog-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@
"typecheck": "tsc --project ./tsconfig.json --noEmit",
"lint": "eslint . --ext .ts,.tsx,.js,.jsx",
"fix:staged-files": "lint-staged --allow-empty",
"fix:all-files": "eslint . --ext .ts,.tsx,.js,.jsx --fix",
"postinstall": "yarn share:static:symlink"
"fix:all-files": "eslint . --ext .ts,.tsx,.js,.jsx --fix"
},
"devDependencies": {
"@emotion/babel-plugin": "^11.3.0",
Expand Down
7 changes: 6 additions & 1 deletion apps/web-app/.env
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# This is the main file for environment
# https://nextjs.org/docs/basic-features/environment-variables

PRISMA_DATABASE_URL="file:../data/prisma-dev-database.sqlite"

# DATABASE_URL
# When deploying on serveless/lambdas "?connection_limit=" should be 1
# @see https://www.prisma.io/docs/concepts/components/prisma-client/deployment#recommended-connection-limit
PRISMA_DATABASE_URL=postgresql://nextjs:!ChangeMe!@localhost:5432/maindb?schema=public

# Enable display of lambdas size for vercel deployments
# NEXT_DEBUG_FUNCTION_SIZE=1
1 change: 1 addition & 0 deletions apps/web-app/.env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
PRISMA_DATABASE_URL=postgresql://nextjs:!ChangeMe!@localhost:5432/maindb?schema=public
61 changes: 57 additions & 4 deletions apps/web-app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,63 @@

> Part of the [nextjs-monorepo-example](https://github.com/belgattitude/nextjs-monorepo-example)
## Develop
## Quick start

### Step 1: Database

This project uses [Prisma](https://prisma.io) as primary database layer an connect
to a postgresql database. An example schema is defined in [./prisma/schema.prisma](./prisma/schema.prisma),
seeds are available in [./prisma/seeds.ts](./prisma/seed.ts).

#### Option 1: Postgresql local

The default env for PRISMA_DATABASE_URL is defined in the main [.env](.env) file.
By default, it connects to the postgresql service defined in [../../docker-compose.yml](../../docker-compose.yml).

Ensure you have docker and docker-compose and run

```bash
# In the root folder
$ docker-compose up database
# Alternatively, from any folder
$ yarn docker:up
```

#### Option 2: An hosted postgres instance

To quick start, you can use a free tier at supabase.io, but all providers will work.

As an example, simply create an `.env.local` and set the supabase pgbouncer url:

```env
PRISMA_DATABASE_URL=postgresql://postgres:[PASSWORD]@[HOST]:[PORT]/postgres?schema=public&pgbouncer=true&sslmode=require&sslaccept=strict&sslcert=../config/certs/supabase-prod-ca-2021.crt
```

> You can append `&connection_limit=1` if deploying on a serverless/lambda provider (ie: vercel, netlify...)
### Step 2:

Create and seed the database the first time or after a change.

```bash
$ cd apps/web-app
$ yarn dev -p 3001
# Alternatively: yarn workspace webapp run dev -p 3000
# Using push here rather than migrate it's easier for
# the example.
$ yarn prisma:db:push
$ yarn prisma:db:seed
```

> **Warning**. Notice how we use ':' rather than spaces. Why ? Cause prisma
> [does not support](https://github.com/prisma/prisma/issues/3865) the .env.[local|development...] supported by nextjs.
> Curious ? Open the package.json script folder to see how we use dotenv-flow under the hood read [this](https://github.com/prisma/prisma/issues/3865).
## Nextjs

### Develop

```
$ yarn dev
```

To test the api/db browse to

- http://localhost:3000/api/rest/post/1
23 changes: 23 additions & 0 deletions apps/web-app/config/certs/supabase-prod-ca-2021.crt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
-----BEGIN CERTIFICATE-----
MIIDxDCCAqygAwIBAgIUbLxMod62P2ktCiAkxnKJwtE9VPYwDQYJKoZIhvcNAQEL
BQAwazELMAkGA1UEBhMCVVMxEDA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dtTl4uUQnSuv/Qx
Cea13BX2ZgJc7Au30vihLhub52De4P/4gonKsNHYdbWjg7OWKwNv/zitGDVDB9Y2
CMTyZKG3XEu5Ghl1LEnI3QmEKsqaCLv12BnVjbkSeZsMnevJPs1Ye6TjjJwdik5P
o/bKiIz+Fq8=
-----END CERTIFICATE-----
Binary file removed apps/web-app/data/prisma-dev-database.sqlite
Binary file not shown.
8 changes: 5 additions & 3 deletions apps/web-app/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ const { compilerOptions: baseTsConfig } = require('./tsconfig.json');
// Take the paths from tsconfig automatically from base tsconfig.json
// @link https://kulshekhar.github.io/ts-jest/docs/paths-mapping
const getTsConfigBasePaths = () => {
return pathsToModuleNameMapper(baseTsConfig.paths, {
prefix: '<rootDir>/',
});
return baseTsConfig.paths
? pathsToModuleNameMapper(baseTsConfig.paths, {
prefix: '<rootDir>/',
})
: {};
};

/** @typedef {import('ts-jest')} */
Expand Down
18 changes: 17 additions & 1 deletion apps/web-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
"vercel-build": "yarn share:static:hardlink && cross-env NEXTJS_BUILD_TARGET=serverless next build",
"clean": "rimraf --no-glob ./.next ./out",
"start": "next start",
"prisma:migrate:reset": "dotenv-flow -- yarn prisma migrate reset",
"prisma:db:seed": "dotenv-flow -- yarn prisma db seed --preview-feature",
"prisma:db:push": "dotenv-flow -- yarn prisma db push",
"prisma:studio": "dotenv-flow -- yarn prisma studio",
"?share:static:symlink": "echo 'Use this command to link assets, locales... from shared static folder'",
"share:static:symlink": "rimraf ./public/shared-assets && symlink-dir ../../static/assets ./public/shared-assets",
"?share:static:hardlink": "echo 'Use this command to link assets, locales... from shared static folder'",
Expand All @@ -30,7 +34,11 @@
"typecheck": "tsc --project ./tsconfig.json --noEmit",
"lint": "eslint . --ext .ts,.tsx,.js,.jsx",
"fix:staged-files": "lint-staged --allow-empty",
"fix:all-files": "eslint . --ext .ts,.tsx,.js,.jsx --fix"
"fix:all-files": "eslint . --ext .ts,.tsx,.js,.jsx --fix",
"?ts-node": "Tip: this is only needed for prisma seeds",
"ts-node": "ts-node --compiler-options {\\\"module\\\":\\\"commonjs\\\"}",
"?postinstall": "@todo: the prisma generate seems to be required, but is installed at the root",
"postinstall": "yarn prisma generate"
},
"devDependencies": {
"@emotion/babel-plugin": "^11.3.0",
Expand All @@ -39,6 +47,7 @@
"@testing-library/jest-dom": "^5.12.0",
"@testing-library/react": "^11.2.7",
"@testing-library/react-hooks": "^6.0.0",
"@types/cors": "^2.8.10",
"@types/jest": "^26.0.23",
"@types/node": "^15.6.1",
"@types/react": "^17.0.7",
Expand All @@ -48,6 +57,8 @@
"autoprefixer": "^10.2.5",
"camelcase": "^6.2.0",
"cross-env": "^7.0.3",
"dotenv-flow": "^3.2.0",
"dotenv-flow-cli": "^1.0.0",
"eslint": "^7.27.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "2.23.3",
Expand All @@ -72,6 +83,7 @@
"sync-directory": "^2.2.22",
"tailwindcss": "^2.1.2",
"ts-jest": "^26.5.6",
"ts-node": "^10.0.0",
"typescript": "^4.2.4"
},
"dependencies": {
Expand All @@ -80,10 +92,14 @@
"@headlessui/react": "^1.2.0",
"@heroicons/react": "^1.0.1",
"@prisma/client": "^2.23.0",
"@tsed/exceptions": "^6.51.0",
"@your-org/core-lib": "workspace:*",
"@your-org/ui-lib": "workspace:*",
"cors": "^2.8.5",
"cross-env": "^7.0.3",
"next": "^10.2.3",
"next-auth": "^3.23.3",
"next-connect": "^0.10.1",
"next-secure-headers": "^2.2.0",
"next-seo": "^4.24.0",
"react": "^17.0.2",
Expand Down
63 changes: 54 additions & 9 deletions apps/web-app/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -1,24 +1,69 @@
datasource db {
provider = "sqlite"
url = env("PRISMA_DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("PRISMA_DATABASE_URL")
}

model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
@@map(name: "post")
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
id Int @id @default(autoincrement())
name String?
email String @unique
emailVerified DateTime? @map(name: "email_verified")
image String?
createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @updatedAt @map(name: "updated_at")
posts Post[]
@@map(name: "user")
}

model AuthAccount {
id Int @id @default(autoincrement())
compoundId String @unique @map(name: "compound_id")
userId Int @map(name: "user_id")
providerType String @map(name: "provider_type")
providerId String @map(name: "provider_id")
providerAccountId String @map(name: "provider_account_id")
refreshToken String? @map(name: "refresh_token")
accessToken String? @map(name: "access_token")
accessTokenExpires DateTime? @map(name: "access_token_expires")
createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @default(now()) @map(name: "updated_at")
@@index([providerAccountId], name: "providerAccountId")
@@index([providerId], name: "providerId")
@@index([userId], name: "userId")
@@map(name: "auth_account")
}

model AuthSession {
id Int @id @default(autoincrement())
userId Int @map(name: "user_id")
expires DateTime
sessionToken String @unique @map(name: "session_token")
accessToken String @unique @map(name: "access_token")
createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @default(now()) @map(name: "updated_at")
@@map(name: "auth_session")
}

model AuthVerificationRequest {
id Int @id @default(autoincrement())
identifier String
token String @unique
expires DateTime
createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @default(now()) @map(name: "updated_at")
@@map(name: "auth_verification_request")
}
Loading

2 comments on commit 754df64

@vercel
Copy link

@vercel vercel bot commented on 754df64 May 26, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on 754df64 May 26, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.