Compare commits
50 Commits
@blitzjs/a
...
@blitzjs/a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c096891bf0 | ||
|
|
81b4b41a99 | ||
|
|
e8271d579c | ||
|
|
9e798b152b | ||
|
|
3c6f43a11d | ||
|
|
8107138e2f | ||
|
|
8cb1134d94 | ||
|
|
2073714f8d | ||
|
|
9631c45833 | ||
|
|
2150dcc3e7 | ||
|
|
63605961b4 | ||
|
|
d711948809 | ||
|
|
1f6b0b54c2 | ||
|
|
4603a2b7bd | ||
|
|
01f3a03ea9 | ||
|
|
36e26193b7 | ||
|
|
4a9aa9f7ff | ||
|
|
1e1bb73b2d | ||
|
|
99205f52d5 | ||
|
|
d03a1165d7 | ||
|
|
d87288a2e9 | ||
|
|
fdff45a592 | ||
|
|
469f55a429 | ||
|
|
e6c31704ed | ||
|
|
35a070ad7d | ||
|
|
9674efc0bf | ||
|
|
666a3ae3e6 | ||
|
|
c9cf7adc33 | ||
|
|
f4c2234c4d | ||
|
|
82916b21c2 | ||
|
|
bf1b2c8244 | ||
|
|
043c3498d0 | ||
|
|
a2ebdbe7d6 | ||
|
|
de4e8084ef | ||
|
|
bb9eaed520 | ||
|
|
ffe85b5ab6 | ||
|
|
6edeed7c5a | ||
|
|
1d9d890d9c | ||
|
|
b8f51a2354 | ||
|
|
6552b11b94 | ||
|
|
d1dd2bc56e | ||
|
|
09b732860d | ||
|
|
ccb6cfd2a0 | ||
|
|
502b8f7820 | ||
|
|
3888d7018a | ||
|
|
02f7822437 | ||
|
|
00bd849eef | ||
|
|
c8db1a0b7e | ||
|
|
fb32903bf9 | ||
|
|
8dedca1a29 |
7
.changeset/breezy-cameras-double.md
Normal file
7
.changeset/breezy-cameras-double.md
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
"blitz": patch
|
||||
"@blitzjs/next": patch
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
Fix codegen and postinstall to make work with pnpm
|
||||
6
.changeset/dirty-monkeys-greet.md
Normal file
6
.changeset/dirty-monkeys-greet.md
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"blitz": patch
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
Use alpha version for blitz dependency, fix package manager selection
|
||||
5
.changeset/empty-berries-rule.md
Normal file
5
.changeset/empty-berries-rule.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
fix app generator for pnpm unmet dependency
|
||||
5
.changeset/fair-wombats-sneeze.md
Normal file
5
.changeset/fair-wombats-sneeze.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/next": patch
|
||||
---
|
||||
|
||||
added superjson
|
||||
5
.changeset/flat-bees-approve.md
Normal file
5
.changeset/flat-bees-approve.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
set default enviornment variable to development unless build and start command
|
||||
9
.changeset/great-months-train.md
Normal file
9
.changeset/great-months-train.md
Normal file
@@ -0,0 +1,9 @@
|
||||
---
|
||||
"blitz": patch
|
||||
"@blitzjs/next": patch
|
||||
"@blitzjs/auth": patch
|
||||
"@blitzjs/rpc": patch
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
fix route manifest codegen
|
||||
5
.changeset/lovely-colts-share.md
Normal file
5
.changeset/lovely-colts-share.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
fix broken cli versioning
|
||||
5
.changeset/nice-starfishes-live.md
Normal file
5
.changeset/nice-starfishes-live.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
add mounted check to app generator template
|
||||
5
.changeset/nine-onions-admire.md
Normal file
5
.changeset/nine-onions-admire.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
downgrade pkg-dir to non-esm only version
|
||||
5
.changeset/poor-shrimps-think.md
Normal file
5
.changeset/poor-shrimps-think.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/next": patch
|
||||
---
|
||||
|
||||
Setup SuperJson for GSSP and GSP
|
||||
@@ -12,7 +12,32 @@
|
||||
"@blitzjs/rpc": "2.0.0-alpha.0",
|
||||
"@blitzjs/config": "0.0.0",
|
||||
"@blitzjs/generator": "2.0.0-alpha.0",
|
||||
"template": "0.0.0"
|
||||
"template": "0.0.0",
|
||||
"toolkit-app": "1.0.0"
|
||||
},
|
||||
"changesets": ["ninety-pets-heal", "poor-peas-lick"]
|
||||
"changesets": [
|
||||
"breezy-cameras-double",
|
||||
"dirty-monkeys-greet",
|
||||
"empty-berries-rule",
|
||||
"fair-wombats-sneeze",
|
||||
"flat-bees-approve",
|
||||
"great-months-train",
|
||||
"lovely-colts-share",
|
||||
"nine-onions-admire",
|
||||
"ninety-pets-heal",
|
||||
"poor-peas-lick",
|
||||
"poor-shrimps-think",
|
||||
"quiet-feet-travel",
|
||||
"sharp-falcons-begin",
|
||||
"silent-colts-reply",
|
||||
"stupid-walls-sell",
|
||||
"swift-drinks-dress",
|
||||
"ten-rivers-burn",
|
||||
"thirty-countries-build",
|
||||
"twenty-beans-pump",
|
||||
"two-kiwis-help",
|
||||
"unlucky-papayas-sleep",
|
||||
"wicked-ghosts-cough",
|
||||
"wise-frogs-give"
|
||||
]
|
||||
}
|
||||
|
||||
5
.changeset/quiet-feet-travel.md
Normal file
5
.changeset/quiet-feet-travel.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
fix source path for templates
|
||||
5
.changeset/sharp-falcons-begin.md
Normal file
5
.changeset/sharp-falcons-begin.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
Use routes manifest in template app
|
||||
5
.changeset/silent-colts-reply.md
Normal file
5
.changeset/silent-colts-reply.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
added index.cjs to blitz externals
|
||||
8
.changeset/stupid-walls-sell.md
Normal file
8
.changeset/stupid-walls-sell.md
Normal file
@@ -0,0 +1,8 @@
|
||||
---
|
||||
"blitz": patch
|
||||
"@blitzjs/auth": patch
|
||||
"@blitzjs/next": patch
|
||||
"@blitzjs/rpc": patch
|
||||
---
|
||||
|
||||
testing set dist-tag
|
||||
5
.changeset/swift-drinks-dress.md
Normal file
5
.changeset/swift-drinks-dress.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/next": patch
|
||||
---
|
||||
|
||||
Fix postinstall script not being found
|
||||
5
.changeset/ten-rivers-burn.md
Normal file
5
.changeset/ten-rivers-burn.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
fix more cli problems
|
||||
5
.changeset/thirty-countries-build.md
Normal file
5
.changeset/thirty-countries-build.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
add @blitzjs/generator as external
|
||||
10
.changeset/twenty-beans-pump.md
Normal file
10
.changeset/twenty-beans-pump.md
Normal file
@@ -0,0 +1,10 @@
|
||||
---
|
||||
"blitz": patch
|
||||
"@blitzjs/auth": patch
|
||||
"@blitzjs/next": patch
|
||||
"@blitzjs/rpc": patch
|
||||
"@blitzjs/config": patch
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
new app template
|
||||
5
.changeset/two-kiwis-help.md
Normal file
5
.changeset/two-kiwis-help.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
fix generate cli command
|
||||
5
.changeset/unlucky-papayas-sleep.md
Normal file
5
.changeset/unlucky-papayas-sleep.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
remove console logs inside onPostInstall in the new cli command
|
||||
5
.changeset/wicked-ghosts-cough.md
Normal file
5
.changeset/wicked-ghosts-cough.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
fix template sourcepath because of new env variable
|
||||
5
.changeset/wise-frogs-give.md
Normal file
5
.changeset/wise-frogs-give.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
use latest tag for generator template on rpc & auth packages
|
||||
37
.github/workflows/release.yml
vendored
Normal file
37
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency: ${{ github.workflow }}-${{ github.ref }}
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Setup Node.js 16.x
|
||||
uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: 16.x
|
||||
|
||||
- name: Pre-publish
|
||||
uses: pnpm/action-setup@646cdf48217256a3d0b80361c5a50727664284f2
|
||||
with:
|
||||
version: 6.32.6
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm changeset version
|
||||
- run: pnpm build
|
||||
|
||||
- name: Create Release Pull Request
|
||||
uses: changesets/action@v1
|
||||
with:
|
||||
publish: pnpm changeset publish
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -62,6 +62,7 @@ examples/auth2
|
||||
.idea
|
||||
.ultra.cache.json
|
||||
db.sqlite-journal
|
||||
**/db/db.sqlite
|
||||
test/integration/**/db.json
|
||||
test/**/*/out
|
||||
test/**/blitz-env.d.ts
|
||||
|
||||
@@ -174,6 +174,7 @@ Your financial contributions help ensure Blitz continues to be developed and mai
|
||||
<tr>
|
||||
<td align="center"><a href="https://twitter.com/flybayer"><img src="https://avatars3.githubusercontent.com/u/8813276?v=4" width="100px;" alt=""/><br /><sub><b>Brandon Bayer</b></sub></a><br />Creator</td>
|
||||
<td align="center"><a href="http://aleksandra.codes"><img src="https://avatars.githubusercontent.com/u/9019397?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Aleksandra Sikora</b></sub></a><br />Lead Maintainer</td>
|
||||
<td align="center"><a href="http://twitter.com/dillonraphael"><img src="https://avatars.githubusercontent.com/u/3496193?v=4" width="100px;" alt=""/><br /><sub><b>Dillon Raphael</b></sub></a><br />Senior Maintainer</td>
|
||||
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
11
apps/toolkit-app/.editorconfig
Normal file
11
apps/toolkit-app/.editorconfig
Normal file
@@ -0,0 +1,11 @@
|
||||
# https://EditorConfig.org
|
||||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_size = 2
|
||||
indent_style = space
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
3
apps/toolkit-app/.env
Normal file
3
apps/toolkit-app/.env
Normal file
@@ -0,0 +1,3 @@
|
||||
# This env file should be checked into source control
|
||||
# This is the place for default values for all environments
|
||||
# Values in `.env.local` and `.env.production` will override these values
|
||||
1
apps/toolkit-app/.eslintrc.js
Normal file
1
apps/toolkit-app/.eslintrc.js
Normal file
@@ -0,0 +1 @@
|
||||
module.exports = require("@blitzjs/next/eslint")
|
||||
56
apps/toolkit-app/.gitignore
vendored
Normal file
56
apps/toolkit-app/.gitignore
vendored
Normal file
@@ -0,0 +1,56 @@
|
||||
# dependencies
|
||||
node_modules
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/sdks
|
||||
!.yarn/versions
|
||||
.pnp.*
|
||||
.npm
|
||||
web_modules/
|
||||
|
||||
# blitz
|
||||
/.blitz/
|
||||
/.next/
|
||||
*.sqlite
|
||||
*.sqlite-journal
|
||||
.now
|
||||
.blitz**
|
||||
blitz-log.log
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
|
||||
# local env files
|
||||
.env.local
|
||||
.env.*.local
|
||||
.envrc
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Testing
|
||||
.coverage
|
||||
*.lcov
|
||||
.nyc_output
|
||||
lib-cov
|
||||
|
||||
# Caches
|
||||
*.tsbuildinfo
|
||||
.eslintcache
|
||||
.node_repl_history
|
||||
.yarn-integrity
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
9
apps/toolkit-app/.prettierignore
Normal file
9
apps/toolkit-app/.prettierignore
Normal file
@@ -0,0 +1,9 @@
|
||||
.gitkeep
|
||||
.env*
|
||||
*.ico
|
||||
*.lock
|
||||
db/migrations
|
||||
.next
|
||||
.yarn
|
||||
.pnp.*
|
||||
node_modules
|
||||
185
apps/toolkit-app/CHANGELOG.md
Normal file
185
apps/toolkit-app/CHANGELOG.md
Normal file
@@ -0,0 +1,185 @@
|
||||
# toolkit-app
|
||||
|
||||
## 1.0.1-alpha.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.21
|
||||
- @blitzjs/auth@2.0.0-alpha.21
|
||||
- @blitzjs/next@2.0.0-alpha.21
|
||||
- @blitzjs/rpc@2.0.0-alpha.21
|
||||
- @blitzjs/config@2.0.0-alpha.21
|
||||
|
||||
## 1.0.1-alpha.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.20
|
||||
- @blitzjs/auth@2.0.0-alpha.20
|
||||
- @blitzjs/next@2.0.0-alpha.20
|
||||
- @blitzjs/rpc@2.0.0-alpha.20
|
||||
- @blitzjs/config@2.0.0-alpha.20
|
||||
|
||||
## 1.0.1-alpha.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- Updated dependencies [2150dcc3]
|
||||
- @blitzjs/next@2.0.0-alpha.19
|
||||
- blitz@2.0.0-alpha.19
|
||||
- @blitzjs/auth@2.0.0-alpha.19
|
||||
- @blitzjs/rpc@2.0.0-alpha.19
|
||||
- @blitzjs/config@2.0.0-alpha.19
|
||||
|
||||
## 1.0.1-alpha.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.18
|
||||
- @blitzjs/auth@2.0.0-alpha.18
|
||||
- @blitzjs/next@2.0.0-alpha.18
|
||||
- @blitzjs/rpc@2.0.0-alpha.18
|
||||
- @blitzjs/config@2.0.0-alpha.18
|
||||
|
||||
## 1.0.1-alpha.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.17
|
||||
- @blitzjs/auth@2.0.0-alpha.17
|
||||
- @blitzjs/next@2.0.0-alpha.17
|
||||
- @blitzjs/rpc@2.0.0-alpha.17
|
||||
- @blitzjs/config@2.0.0-alpha.17
|
||||
|
||||
## 1.0.1-alpha.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.16
|
||||
- @blitzjs/auth@2.0.0-alpha.16
|
||||
- @blitzjs/next@2.0.0-alpha.16
|
||||
- @blitzjs/rpc@2.0.0-alpha.16
|
||||
- @blitzjs/config@2.0.0-alpha.16
|
||||
|
||||
## 1.0.1-alpha.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.15
|
||||
- @blitzjs/auth@2.0.0-alpha.15
|
||||
- @blitzjs/next@2.0.0-alpha.15
|
||||
- @blitzjs/rpc@2.0.0-alpha.15
|
||||
- @blitzjs/config@2.0.0-alpha.15
|
||||
|
||||
## 1.0.1-alpha.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.14
|
||||
- @blitzjs/auth@2.0.0-alpha.14
|
||||
- @blitzjs/next@2.0.0-alpha.14
|
||||
- @blitzjs/rpc@2.0.0-alpha.14
|
||||
- @blitzjs/config@2.0.0-alpha.14
|
||||
|
||||
## 1.0.1-alpha.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.13
|
||||
- @blitzjs/next@2.0.0-alpha.13
|
||||
- @blitzjs/auth@2.0.0-alpha.13
|
||||
- @blitzjs/rpc@2.0.0-alpha.13
|
||||
- @blitzjs/config@2.0.0-alpha.13
|
||||
|
||||
## 1.0.1-alpha.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.12
|
||||
- @blitzjs/auth@2.0.0-alpha.12
|
||||
- @blitzjs/next@2.0.0-alpha.12
|
||||
- @blitzjs/rpc@2.0.0-alpha.12
|
||||
- @blitzjs/config@2.0.0-alpha.12
|
||||
|
||||
## 1.0.1-alpha.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- @blitzjs/next@2.0.0-alpha.11
|
||||
- @blitzjs/auth@2.0.0-alpha.11
|
||||
- @blitzjs/rpc@2.0.0-alpha.11
|
||||
- @blitzjs/config@2.0.0-alpha.11
|
||||
- blitz@2.0.0-alpha.11
|
||||
|
||||
## 1.0.1-alpha.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.10
|
||||
- @blitzjs/auth@2.0.0-alpha.10
|
||||
- @blitzjs/next@2.0.0-alpha.10
|
||||
- @blitzjs/rpc@2.0.0-alpha.10
|
||||
- @blitzjs/config@2.0.0-alpha.10
|
||||
|
||||
## 1.0.1-alpha.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.9
|
||||
- @blitzjs/auth@2.0.0-alpha.9
|
||||
- @blitzjs/next@2.0.0-alpha.9
|
||||
- @blitzjs/rpc@2.0.0-alpha.9
|
||||
- @blitzjs/config@2.0.0-alpha.9
|
||||
|
||||
## 1.0.1-alpha.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.8
|
||||
- @blitzjs/auth@2.0.0-alpha.8
|
||||
- @blitzjs/next@2.0.0-alpha.8
|
||||
- @blitzjs/rpc@2.0.0-alpha.8
|
||||
- @blitzjs/config@2.0.0-alpha.8
|
||||
|
||||
## 1.0.1-alpha.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.7
|
||||
- @blitzjs/auth@2.0.0-alpha.7
|
||||
- @blitzjs/next@2.0.0-alpha.7
|
||||
- @blitzjs/rpc@2.0.0-alpha.7
|
||||
- @blitzjs/config@2.0.0-alpha.7
|
||||
|
||||
## 1.0.1-alpha.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- @blitzjs/next@2.0.0-alpha.6
|
||||
- blitz@2.0.0-alpha.6
|
||||
- @blitzjs/auth@2.0.0-alpha.6
|
||||
- @blitzjs/rpc@2.0.0-alpha.6
|
||||
- @blitzjs/config@2.0.0-alpha.6
|
||||
|
||||
## 1.0.1-alpha.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.5
|
||||
- @blitzjs/auth@2.0.0-alpha.5
|
||||
- @blitzjs/next@2.0.0-alpha.5
|
||||
- @blitzjs/rpc@2.0.0-alpha.5
|
||||
- @blitzjs/config@2.0.0-alpha.5
|
||||
175
apps/toolkit-app/README.md
Normal file
175
apps/toolkit-app/README.md
Normal file
@@ -0,0 +1,175 @@
|
||||
TODO
|
||||
|
||||
[](https://blitzjs.com)
|
||||
|
||||
This is a [Blitz.js](https://github.com/blitz-js/blitz) app.
|
||||
|
||||
# ****name****
|
||||
|
||||
## Getting Started
|
||||
|
||||
Run your app in the development mode.
|
||||
|
||||
```
|
||||
blitz dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Ensure the `.env.local` file has required environment variables:
|
||||
|
||||
```
|
||||
DATABASE_URL=postgresql://<YOUR_DB_USERNAME>@localhost:5432/__name__
|
||||
```
|
||||
|
||||
Ensure the `.env.test.local` file has required environment variables:
|
||||
|
||||
```
|
||||
DATABASE_URL=postgresql://<YOUR_DB_USERNAME>@localhost:5432/__name___test
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
Runs your tests using Jest.
|
||||
|
||||
```
|
||||
yarn test
|
||||
```
|
||||
|
||||
Blitz comes with a test setup using [Jest](https://jestjs.io/) and [react-testing-library](https://testing-library.com/).
|
||||
|
||||
## Commands
|
||||
|
||||
Blitz comes with a powerful CLI that is designed to make development easy and fast. You can install it with `npm i -g blitz`
|
||||
|
||||
```
|
||||
blitz [COMMAND]
|
||||
|
||||
dev Start a development server
|
||||
build Create a production build
|
||||
start Start a production server
|
||||
export Export your Blitz app as a static application
|
||||
prisma Run prisma commands
|
||||
generate Generate new files for your Blitz project
|
||||
console Run the Blitz console REPL
|
||||
install Install a recipe
|
||||
help Display help for blitz
|
||||
test Run project tests
|
||||
```
|
||||
|
||||
You can read more about it on the [CLI Overview](https://blitzjs.com/docs/cli-overview) documentation.
|
||||
|
||||
## What's included?
|
||||
|
||||
Here is the starting structure of your app.
|
||||
|
||||
```
|
||||
__name__
|
||||
├── app/
|
||||
│ ├── api/
|
||||
│ ├── auth/
|
||||
│ │ ├── components/
|
||||
│ │ │ ├── LoginForm.tsx
|
||||
│ │ │ └── SignupForm.tsx
|
||||
│ │ ├── mutations/
|
||||
│ │ │ ├── changePassword.ts
|
||||
│ │ │ ├── forgotPassword.test.ts
|
||||
│ │ │ ├── forgotPassword.ts
|
||||
│ │ │ ├── login.ts
|
||||
│ │ │ ├── logout.ts
|
||||
│ │ │ ├── resetPassword.test.ts
|
||||
│ │ │ ├── resetPassword.ts
|
||||
│ │ │ └── signup.ts
|
||||
│ │ ├── pages/
|
||||
│ │ │ ├── forgot-password.tsx
|
||||
│ │ │ ├── login.tsx
|
||||
│ │ │ ├── reset-password.tsx
|
||||
│ │ │ └── signup.tsx
|
||||
│ │ └── validations.ts
|
||||
│ ├── core/
|
||||
│ │ ├── components/
|
||||
│ │ │ ├── Form.tsx
|
||||
│ │ │ └── LabeledTextField.tsx
|
||||
│ │ ├── hooks/
|
||||
│ │ │ └── useCurrentUser.ts
|
||||
│ │ └── layouts/
|
||||
│ │ └── Layout.tsx
|
||||
│ ├── pages/
|
||||
│ │ ├── _app.tsx
|
||||
│ │ ├── _document.tsx
|
||||
│ │ ├── 404.tsx
|
||||
│ │ ├── index.test.tsx
|
||||
│ │ └── index.tsx
|
||||
│ └── users/
|
||||
│ └── queries/
|
||||
│ └── getCurrentUser.ts
|
||||
├── db/
|
||||
│ ├── migrations/
|
||||
│ ├── index.ts
|
||||
│ ├── schema.prisma
|
||||
│ └── seeds.ts
|
||||
├── integrations/
|
||||
├── mailers/
|
||||
│ └── forgotPasswordMailer.ts
|
||||
├── public/
|
||||
│ ├── favicon.ico
|
||||
│ └── logo.png
|
||||
├── test/
|
||||
│ ├── setup.ts
|
||||
│ └── utils.tsx
|
||||
├── .eslintrc.js
|
||||
├── babel.config.js
|
||||
├── blitz.config.ts
|
||||
├── jest.config.ts
|
||||
├── package.json
|
||||
├── README.md
|
||||
├── tsconfig.json
|
||||
└── types.ts
|
||||
```
|
||||
|
||||
These files are:
|
||||
|
||||
- The `app/` folder is a container for most of your project. This is where you’ll put any pages or API routes.
|
||||
|
||||
- `db/` is where your database configuration goes. If you’re writing models or checking migrations, this is where to go.
|
||||
|
||||
- `public/` is a folder where you will put any static assets. If you have images, files, or videos which you want to use in your app, this is where to put them.
|
||||
|
||||
- `integrations/` is a folder to put all third-party integrations like with Stripe, Sentry, etc.
|
||||
|
||||
- `test/` is a folder where you can put test utilities and integration tests.
|
||||
|
||||
- `package.json` contains information about your dependencies and devDependencies. If you’re using a tool like `npm` or `yarn`, you won’t have to worry about this much.
|
||||
|
||||
- `tsconfig.json` is our recommended setup for TypeScript.
|
||||
|
||||
- `.babel.config.js`, `.eslintrc.js`, `.env`, etc. ("dotfiles") are configuration files for various bits of JavaScript tooling.
|
||||
|
||||
- `blitz.config.ts` is for advanced custom configuration of Blitz. [Here you can learn how to use it](https://blitzjs.com/docs/blitz-config).
|
||||
|
||||
- `jest.config.js` contains config for Jest tests. You can [customize it if needed](https://jestjs.io/docs/en/configuration).
|
||||
|
||||
You can read more about it in the [File Structure](https://blitzjs.com/docs/file-structure) section of the documentation.
|
||||
|
||||
### Tools included
|
||||
|
||||
Blitz comes with a set of tools that corrects and formats your code, facilitating its future maintenance. You can modify their options and even uninstall them.
|
||||
|
||||
- **ESLint**: It lints your code: searches for bad practices and tell you about it. You can customize it via the `.eslintrc.js`, and you can install (or even write) plugins to have it the way you like it. It already comes with the [`blitz`](https://github.com/blitz-js/blitz/tree/canary/packages/eslint-config) config, but you can remove it safely. [Learn More](https://blitzjs.com/docs/eslint-config).
|
||||
- **Husky**: It adds [githooks](https://git-scm.com/docs/githooks), little pieces of code that get executed when certain Git events are triggerd. For example, `pre-commit` is triggered just before a commit is created. You can see the current hooks inside `.husky/`. If are having problems commiting and pushing, check out ther [troubleshooting](https://typicode.github.io/husky/#/?id=troubleshoot) guide. [Learn More](https://blitzjs.com/docs/husky-config).
|
||||
- **Prettier**: It formats your code to look the same everywhere. You can configure it via the `.prettierrc` file. The `.prettierignore` contains the files that should be ignored by Prettier; useful when you have large files or when you want to keep a custom formatting. [Learn More](https://blitzjs.com/docs/prettier-config).
|
||||
|
||||
## Learn more
|
||||
|
||||
Read the [Blitz.js Documentation](https://blitzjs.com/docs/getting-started) to learn more.
|
||||
|
||||
The Blitz community is warm, safe, diverse, inclusive, and fun! Feel free to reach out to us in any of our communication channels.
|
||||
|
||||
- [Website](https://blitzjs.com)
|
||||
- [Discord](https://blitzjs.com/discord)
|
||||
- [Report an issue](https://github.com/blitz-js/blitz/issues/new/choose)
|
||||
- [Forum discussions](https://github.com/blitz-js/blitz/discussions)
|
||||
- [How to Contribute](https://blitzjs.com/docs/contributing)
|
||||
- [Sponsor or donate](https://github.com/blitz-js/blitz#sponsors-and-donations)
|
||||
59
apps/toolkit-app/app/auth/components/LoginForm.tsx
Normal file
59
apps/toolkit-app/app/auth/components/LoginForm.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import { AuthenticationError, PromiseReturnType } from "blitz"
|
||||
import Link from "next/link"
|
||||
import { LabeledTextField } from "app/core/components/LabeledTextField"
|
||||
import { Form, FORM_ERROR } from "app/core/components/Form"
|
||||
import login from "app/auth/mutations/login"
|
||||
import { Login } from "app/auth/validations"
|
||||
import { useMutation } from "@blitzjs/rpc"
|
||||
import { Routes } from "@blitzjs/next"
|
||||
|
||||
type LoginFormProps = {
|
||||
onSuccess?: (user: PromiseReturnType<typeof login>) => void
|
||||
}
|
||||
|
||||
export const LoginForm = (props: LoginFormProps) => {
|
||||
const [loginMutation] = useMutation(login)
|
||||
return (
|
||||
<div>
|
||||
<h1>Login</h1>
|
||||
|
||||
<Form
|
||||
submitText="Login"
|
||||
schema={Login}
|
||||
initialValues={{ email: "", password: "" }}
|
||||
onSubmit={async (values) => {
|
||||
try {
|
||||
const user = await loginMutation(values)
|
||||
props.onSuccess?.(user)
|
||||
} catch (error: any) {
|
||||
if (error instanceof AuthenticationError) {
|
||||
return { [FORM_ERROR]: "Sorry, those credentials are invalid" }
|
||||
} else {
|
||||
return {
|
||||
[FORM_ERROR]:
|
||||
"Sorry, we had an unexpected error. Please try again. - " + error.toString(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}}
|
||||
>
|
||||
<LabeledTextField name="email" label="Email" placeholder="Email" />
|
||||
<LabeledTextField name="password" label="Password" placeholder="Password" type="password" />
|
||||
<div>
|
||||
<Link href={Routes.ForgotPasswordPage()} passHref>
|
||||
<a>Forgot your password?</a>
|
||||
</Link>
|
||||
</div>
|
||||
</Form>
|
||||
|
||||
<div style={{ marginTop: "1rem" }}>
|
||||
Or{" "}
|
||||
<Link href={Routes.SignupPage()} passHref>
|
||||
<a>Sign Up</a>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default LoginForm
|
||||
42
apps/toolkit-app/app/auth/components/SignupForm.tsx
Normal file
42
apps/toolkit-app/app/auth/components/SignupForm.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
import { LabeledTextField } from "app/core/components/LabeledTextField"
|
||||
import { Form, FORM_ERROR } from "app/core/components/Form"
|
||||
import signup from "app/auth/mutations/signup"
|
||||
import { Signup } from "app/auth/validations"
|
||||
import { useMutation } from "@blitzjs/rpc"
|
||||
|
||||
type SignupFormProps = {
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export const SignupForm = (props: SignupFormProps) => {
|
||||
const [signupMutation] = useMutation(signup)
|
||||
return (
|
||||
<div>
|
||||
<h1>Create an Account</h1>
|
||||
|
||||
<Form
|
||||
submitText="Create Account"
|
||||
schema={Signup}
|
||||
initialValues={{ email: "", password: "" }}
|
||||
onSubmit={async (values) => {
|
||||
try {
|
||||
await signupMutation(values)
|
||||
props.onSuccess?.()
|
||||
} catch (error: any) {
|
||||
if (error.code === "P2002" && error.meta?.target?.includes("email")) {
|
||||
// This error comes from Prisma
|
||||
return { email: "This email is already being used" }
|
||||
} else {
|
||||
return { [FORM_ERROR]: error.toString() }
|
||||
}
|
||||
}
|
||||
}}
|
||||
>
|
||||
<LabeledTextField name="email" label="Email" placeholder="Email" />
|
||||
<LabeledTextField name="password" label="Password" placeholder="Password" type="password" />
|
||||
</Form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SignupForm
|
||||
25
apps/toolkit-app/app/auth/mutations/changePassword.ts
Normal file
25
apps/toolkit-app/app/auth/mutations/changePassword.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { NotFoundError } from "blitz"
|
||||
import { db } from "db"
|
||||
import { authenticateUser } from "./login"
|
||||
import { ChangePassword } from "../validations"
|
||||
import { resolver } from "@blitzjs/rpc"
|
||||
import { SecurePassword } from "@blitzjs/auth"
|
||||
|
||||
export default resolver.pipe(
|
||||
resolver.zod(ChangePassword),
|
||||
resolver.authorize(),
|
||||
async ({ currentPassword, newPassword }, ctx) => {
|
||||
const user = await db.user.findFirst({ where: { id: ctx.session.userId as number } })
|
||||
if (!user) throw new NotFoundError()
|
||||
|
||||
await authenticateUser(user.email, currentPassword)
|
||||
|
||||
const hashedPassword = await SecurePassword.hash(newPassword.trim())
|
||||
await db.user.update({
|
||||
where: { id: user.id },
|
||||
data: { hashedPassword },
|
||||
})
|
||||
|
||||
return true
|
||||
}
|
||||
)
|
||||
42
apps/toolkit-app/app/auth/mutations/forgotPassword.ts
Normal file
42
apps/toolkit-app/app/auth/mutations/forgotPassword.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { generateToken, hash256 } from "@blitzjs/auth"
|
||||
import { resolver } from "@blitzjs/rpc"
|
||||
import { db } from "db"
|
||||
import { forgotPasswordMailer } from "mailers/forgotPasswordMailer"
|
||||
import { ForgotPassword } from "../validations"
|
||||
|
||||
const RESET_PASSWORD_TOKEN_EXPIRATION_IN_HOURS = 4
|
||||
|
||||
export default resolver.pipe(resolver.zod(ForgotPassword), async ({ email }) => {
|
||||
// 1. Get the user
|
||||
const user = await db.user.findFirst({ where: { email: email.toLowerCase() } })
|
||||
|
||||
// 2. Generate the token and expiration date.
|
||||
const token = generateToken()
|
||||
const hashedToken = hash256(token)
|
||||
const expiresAt = new Date()
|
||||
expiresAt.setHours(expiresAt.getHours() + RESET_PASSWORD_TOKEN_EXPIRATION_IN_HOURS)
|
||||
|
||||
// 3. If user with this email was found
|
||||
if (user) {
|
||||
// 4. Delete any existing password reset tokens
|
||||
await db.token.deleteMany({ where: { type: "RESET_PASSWORD", userId: user.id } })
|
||||
// 5. Save this new token in the database.
|
||||
await db.token.create({
|
||||
data: {
|
||||
user: { connect: { id: user.id } },
|
||||
type: "RESET_PASSWORD",
|
||||
expiresAt,
|
||||
hashedToken,
|
||||
sentTo: user.email,
|
||||
},
|
||||
})
|
||||
// 6. Send the email
|
||||
await forgotPasswordMailer({ to: user.email, token }).send()
|
||||
} else {
|
||||
// 7. If no user found wait the same time so attackers can't tell the difference
|
||||
await new Promise((resolve) => setTimeout(resolve, 750))
|
||||
}
|
||||
|
||||
// 8. Return the same result whether a password reset email was sent or not
|
||||
return
|
||||
})
|
||||
32
apps/toolkit-app/app/auth/mutations/login.ts
Normal file
32
apps/toolkit-app/app/auth/mutations/login.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { SecurePassword } from "@blitzjs/auth"
|
||||
import { resolver } from "@blitzjs/rpc"
|
||||
import { AuthenticationError } from "blitz"
|
||||
import { db } from "db"
|
||||
import { Role } from "types"
|
||||
import { Login } from "../validations"
|
||||
|
||||
export const authenticateUser = async (rawEmail: string, rawPassword: string) => {
|
||||
const { email, password } = Login.parse({ email: rawEmail, password: rawPassword })
|
||||
const user = await db.user.findFirst({ where: { email } })
|
||||
if (!user) throw new AuthenticationError()
|
||||
|
||||
const result = await SecurePassword.verify(user.hashedPassword, password)
|
||||
|
||||
if (result === SecurePassword.VALID_NEEDS_REHASH) {
|
||||
// Upgrade hashed password with a more secure hash
|
||||
const improvedHash = await SecurePassword.hash(password)
|
||||
await db.user.update({ where: { id: user.id }, data: { hashedPassword: improvedHash } })
|
||||
}
|
||||
|
||||
const { hashedPassword, ...rest } = user
|
||||
return rest
|
||||
}
|
||||
|
||||
export default resolver.pipe(resolver.zod(Login), async ({ email, password }, ctx) => {
|
||||
// This throws an error if credentials are invalid
|
||||
const user = await authenticateUser(email, password)
|
||||
|
||||
await ctx.session.$create({ userId: user.id, role: user.role as Role })
|
||||
|
||||
return user
|
||||
})
|
||||
5
apps/toolkit-app/app/auth/mutations/logout.ts
Normal file
5
apps/toolkit-app/app/auth/mutations/logout.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Ctx } from "blitz"
|
||||
|
||||
export default async function logout(_: any, ctx: Ctx) {
|
||||
return await ctx.session.$revoke()
|
||||
}
|
||||
48
apps/toolkit-app/app/auth/mutations/resetPassword.ts
Normal file
48
apps/toolkit-app/app/auth/mutations/resetPassword.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { SecurePassword, hash256 } from "@blitzjs/auth"
|
||||
import { db } from "db"
|
||||
import { ResetPassword } from "../validations"
|
||||
import login from "./login"
|
||||
|
||||
export class ResetPasswordError extends Error {
|
||||
name = "ResetPasswordError"
|
||||
message = "Reset password link is invalid or it has expired."
|
||||
}
|
||||
|
||||
export default async function resetPassword(input, ctx) {
|
||||
ResetPassword.parse(input)
|
||||
// 1. Try to find this token in the database
|
||||
const hashedToken = hash256(input.token)
|
||||
const possibleToken = await db.token.findFirst({
|
||||
where: { hashedToken, type: "RESET_PASSWORD" },
|
||||
include: { user: true },
|
||||
})
|
||||
|
||||
// 2. If token not found, error
|
||||
if (!possibleToken) {
|
||||
throw new ResetPasswordError()
|
||||
}
|
||||
const savedToken = possibleToken
|
||||
|
||||
// 3. Delete token so it can't be used again
|
||||
await db.token.delete({ where: { id: savedToken.id } })
|
||||
|
||||
// 4. If token has expired, error
|
||||
if (savedToken.expiresAt < new Date()) {
|
||||
throw new ResetPasswordError()
|
||||
}
|
||||
|
||||
// 5. Since token is valid, now we can update the user's password
|
||||
const hashedPassword = await SecurePassword.hash(input.password.trim())
|
||||
const user = await db.user.update({
|
||||
where: { id: savedToken.userId },
|
||||
data: { hashedPassword },
|
||||
})
|
||||
|
||||
// 6. Revoke all existing login sessions for this user
|
||||
await db.session.deleteMany({ where: { userId: user.id } })
|
||||
|
||||
// 7. Now log the user in with the new credentials
|
||||
await login({ email: user.email, password: input.password }, ctx)
|
||||
|
||||
return true
|
||||
}
|
||||
19
apps/toolkit-app/app/auth/mutations/signup.ts
Normal file
19
apps/toolkit-app/app/auth/mutations/signup.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { db } from "db"
|
||||
import { SecurePassword } from "@blitzjs/auth"
|
||||
|
||||
export default async function signup(input, ctx) {
|
||||
const blitzContext = ctx
|
||||
|
||||
const hashedPassword = await SecurePassword.hash((input.password as string) || "test-password")
|
||||
const email = (input.email as string) || "test" + Math.random() + "@test.com"
|
||||
const user = await db.user.create({
|
||||
data: { email, hashedPassword, role: "user" },
|
||||
select: { id: true, name: true, email: true, role: true },
|
||||
})
|
||||
|
||||
await blitzContext.session.$create({
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
return { userId: blitzContext.session.userId, ...user, email: input.email }
|
||||
}
|
||||
42
apps/toolkit-app/app/auth/validations.ts
Normal file
42
apps/toolkit-app/app/auth/validations.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const email = z
|
||||
.string()
|
||||
.email()
|
||||
.transform((str) => str.toLowerCase().trim())
|
||||
|
||||
export const password = z
|
||||
.string()
|
||||
.min(10)
|
||||
.max(100)
|
||||
.transform((str) => str.trim())
|
||||
|
||||
export const Signup = z.object({
|
||||
email,
|
||||
password,
|
||||
})
|
||||
|
||||
export const Login = z.object({
|
||||
email,
|
||||
password: z.string(),
|
||||
})
|
||||
|
||||
export const ForgotPassword = z.object({
|
||||
email,
|
||||
})
|
||||
|
||||
export const ResetPassword = z
|
||||
.object({
|
||||
password: password,
|
||||
passwordConfirmation: password,
|
||||
token: z.string(),
|
||||
})
|
||||
.refine((data) => data.password === data.passwordConfirmation, {
|
||||
message: "Passwords don't match",
|
||||
path: ["passwordConfirmation"], // set the path of the error
|
||||
})
|
||||
|
||||
export const ChangePassword = z.object({
|
||||
currentPassword: z.string(),
|
||||
newPassword: password,
|
||||
})
|
||||
18
apps/toolkit-app/app/blitz-client.ts
Normal file
18
apps/toolkit-app/app/blitz-client.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { AuthClientPlugin } from "@blitzjs/auth"
|
||||
import { setupBlitzClient } from "@blitzjs/next"
|
||||
import { BlitzRpcPlugin } from "@blitzjs/rpc"
|
||||
|
||||
export const { withBlitz } = setupBlitzClient({
|
||||
plugins: [
|
||||
AuthClientPlugin({
|
||||
cookiePrefix: "web-cookie-prefix",
|
||||
}),
|
||||
BlitzRpcPlugin({
|
||||
reactQueryOptions: {
|
||||
queries: {
|
||||
staleTime: 7000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
})
|
||||
17
apps/toolkit-app/app/blitz-server.ts
Normal file
17
apps/toolkit-app/app/blitz-server.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { setupBlitzServer } from "@blitzjs/next"
|
||||
import { AuthServerPlugin, PrismaStorage } from "@blitzjs/auth"
|
||||
import { db } from "db"
|
||||
import { simpleRolesIsAuthorized } from "@blitzjs/auth"
|
||||
|
||||
const { gSSP, gSP, api } = setupBlitzServer({
|
||||
plugins: [
|
||||
AuthServerPlugin({
|
||||
cookiePrefix: "web-cookie-prefix",
|
||||
// TODO fix type
|
||||
storage: PrismaStorage(db as any),
|
||||
isAuthorized: simpleRolesIsAuthorized,
|
||||
}),
|
||||
],
|
||||
})
|
||||
|
||||
export { gSSP, gSP, api }
|
||||
83
apps/toolkit-app/app/core/components/Form.tsx
Normal file
83
apps/toolkit-app/app/core/components/Form.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
import { useState, ReactNode, PropsWithoutRef } from "react"
|
||||
import { FormProvider, useForm, UseFormProps } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { z } from "zod"
|
||||
|
||||
export interface FormProps<S extends z.ZodType<any, any>>
|
||||
extends Omit<PropsWithoutRef<JSX.IntrinsicElements["form"]>, "onSubmit"> {
|
||||
/** All your form fields */
|
||||
children?: ReactNode
|
||||
/** Text to display in the submit button */
|
||||
submitText?: string
|
||||
schema?: S
|
||||
onSubmit: (values: z.infer<S>) => Promise<void | OnSubmitResult>
|
||||
initialValues?: UseFormProps<z.infer<S>>["defaultValues"]
|
||||
}
|
||||
|
||||
interface OnSubmitResult {
|
||||
FORM_ERROR?: string
|
||||
[prop: string]: any
|
||||
}
|
||||
|
||||
export const FORM_ERROR = "FORM_ERROR"
|
||||
|
||||
export function Form<S extends z.ZodType<any, any>>({
|
||||
children,
|
||||
submitText,
|
||||
schema,
|
||||
initialValues,
|
||||
onSubmit,
|
||||
...props
|
||||
}: FormProps<S>) {
|
||||
const ctx = useForm<z.infer<S>>({
|
||||
mode: "onBlur",
|
||||
resolver: schema ? zodResolver(schema) : undefined,
|
||||
defaultValues: initialValues,
|
||||
})
|
||||
const [formError, setFormError] = useState<string | null>(null)
|
||||
|
||||
return (
|
||||
<FormProvider {...ctx}>
|
||||
<form
|
||||
onSubmit={ctx.handleSubmit(async (values) => {
|
||||
const result = (await onSubmit(values)) || {}
|
||||
for (const [key, value] of Object.entries(result)) {
|
||||
if (key === FORM_ERROR) {
|
||||
setFormError(value)
|
||||
} else {
|
||||
ctx.setError(key as any, {
|
||||
type: "submit",
|
||||
message: value,
|
||||
})
|
||||
}
|
||||
}
|
||||
})}
|
||||
className="form"
|
||||
{...props}
|
||||
>
|
||||
{/* Form fields supplied as children are rendered here */}
|
||||
{children}
|
||||
|
||||
{formError && (
|
||||
<div role="alert" style={{ color: "red" }}>
|
||||
{formError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{submitText && (
|
||||
<button type="submit" disabled={ctx.formState.isSubmitting}>
|
||||
{submitText}
|
||||
</button>
|
||||
)}
|
||||
|
||||
<style global jsx>{`
|
||||
.form > * + * {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
`}</style>
|
||||
</form>
|
||||
</FormProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export default Form
|
||||
59
apps/toolkit-app/app/core/components/LabeledTextField.tsx
Normal file
59
apps/toolkit-app/app/core/components/LabeledTextField.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import { forwardRef, PropsWithoutRef, ComponentPropsWithoutRef } from "react"
|
||||
import { useFormContext } from "react-hook-form"
|
||||
|
||||
export interface LabeledTextFieldProps extends PropsWithoutRef<JSX.IntrinsicElements["input"]> {
|
||||
/** Field name. */
|
||||
name: string
|
||||
/** Field label. */
|
||||
label: string
|
||||
/** Field type. Doesn't include radio buttons and checkboxes */
|
||||
type?: "text" | "password" | "email" | "number"
|
||||
outerProps?: PropsWithoutRef<JSX.IntrinsicElements["div"]>
|
||||
labelProps?: ComponentPropsWithoutRef<"label">
|
||||
}
|
||||
|
||||
export const LabeledTextField = forwardRef<HTMLInputElement, LabeledTextFieldProps>(
|
||||
({ label, outerProps, labelProps, name, ...props }, ref) => {
|
||||
const {
|
||||
register,
|
||||
formState: { isSubmitting, errors },
|
||||
} = useFormContext()
|
||||
const error = Array.isArray(errors[name])
|
||||
? errors[name].join(", ")
|
||||
: errors[name]?.message || errors[name]
|
||||
|
||||
return (
|
||||
<div {...outerProps}>
|
||||
<label {...labelProps}>
|
||||
{label}
|
||||
<input disabled={isSubmitting} {...register(name)} {...props} />
|
||||
</label>
|
||||
|
||||
{error && (
|
||||
<div role="alert" style={{ color: "red" }}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<style jsx>{`
|
||||
label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: start;
|
||||
font-size: 1rem;
|
||||
}
|
||||
input {
|
||||
font-size: 1rem;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 3px;
|
||||
border: 1px solid purple;
|
||||
appearance: none;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
export default LabeledTextField
|
||||
7
apps/toolkit-app/app/core/hooks/useCurrentUser.ts
Normal file
7
apps/toolkit-app/app/core/hooks/useCurrentUser.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { useQuery } from "@blitzjs/rpc"
|
||||
import getCurrentUser from "app/users/queries/getCurrentUser"
|
||||
|
||||
export const useCurrentUser = () => {
|
||||
const [user] = useQuery(getCurrentUser, null)
|
||||
return user
|
||||
}
|
||||
17
apps/toolkit-app/app/core/layouts/Layout.tsx
Normal file
17
apps/toolkit-app/app/core/layouts/Layout.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import Head from "next/head"
|
||||
import React, { FC } from "react"
|
||||
|
||||
const Layout: FC<{ title?: string; children?: React.ReactNode }> = ({ title, children }) => {
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{title || "__name__"}</title>
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
|
||||
{children}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default Layout
|
||||
13
apps/toolkit-app/app/users/queries/getCurrentUser.ts
Normal file
13
apps/toolkit-app/app/users/queries/getCurrentUser.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { Ctx } from "blitz"
|
||||
import { db } from "db"
|
||||
|
||||
export default async function getCurrentUser(_ = null, { session }: Ctx) {
|
||||
if (!session.userId) return null
|
||||
|
||||
const user = await db.user.findFirst({
|
||||
where: { id: session.userId as number },
|
||||
select: { id: true, name: true, email: true, role: true },
|
||||
})
|
||||
|
||||
return user
|
||||
}
|
||||
8
apps/toolkit-app/db/index.ts
Normal file
8
apps/toolkit-app/db/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { enhancePrisma } from "blitz"
|
||||
import { PrismaClient } from "@prisma/client"
|
||||
|
||||
const EnhancedPrisma = enhancePrisma(PrismaClient)
|
||||
|
||||
export * from "@prisma/client"
|
||||
const db = new EnhancedPrisma()
|
||||
export { db }
|
||||
47
apps/toolkit-app/db/migrations/20220427214932_/migration.sql
Normal file
47
apps/toolkit-app/db/migrations/20220427214932_/migration.sql
Normal file
@@ -0,0 +1,47 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "User" (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" DATETIME NOT NULL,
|
||||
"name" TEXT,
|
||||
"email" TEXT NOT NULL,
|
||||
"hashedPassword" TEXT,
|
||||
"role" TEXT NOT NULL DEFAULT 'USER'
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Session" (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" DATETIME NOT NULL,
|
||||
"expiresAt" DATETIME,
|
||||
"handle" TEXT NOT NULL,
|
||||
"hashedSessionToken" TEXT,
|
||||
"antiCSRFToken" TEXT,
|
||||
"publicData" TEXT,
|
||||
"privateData" TEXT,
|
||||
"userId" INTEGER,
|
||||
CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE SET NULL ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Token" (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" DATETIME NOT NULL,
|
||||
"hashedToken" TEXT NOT NULL,
|
||||
"type" TEXT NOT NULL,
|
||||
"expiresAt" DATETIME NOT NULL,
|
||||
"sentTo" TEXT NOT NULL,
|
||||
"userId" INTEGER NOT NULL,
|
||||
CONSTRAINT "Token_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Session_handle_key" ON "Session"("handle");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Token_hashedToken_type_key" ON "Token"("hashedToken", "type");
|
||||
3
apps/toolkit-app/db/migrations/migration_lock.toml
Normal file
3
apps/toolkit-app/db/migrations/migration_lock.toml
Normal file
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (i.e. Git)
|
||||
provider = "sqlite"
|
||||
65
apps/toolkit-app/db/schema.prisma
Normal file
65
apps/toolkit-app/db/schema.prisma
Normal file
@@ -0,0 +1,65 @@
|
||||
// This is your Prisma schema file,
|
||||
// learn more about it in the docs: https://pris.ly/d/prisma-schema
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = "file:./db.sqlite"
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
// --------------------------------------
|
||||
|
||||
model User {
|
||||
id Int @id @default(autoincrement())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
name String?
|
||||
email String @unique
|
||||
hashedPassword String?
|
||||
role String @default("USER")
|
||||
|
||||
tokens Token[]
|
||||
sessions Session[]
|
||||
}
|
||||
|
||||
model Session {
|
||||
id Int @id @default(autoincrement())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
expiresAt DateTime?
|
||||
handle String @unique
|
||||
hashedSessionToken String?
|
||||
antiCSRFToken String?
|
||||
publicData String?
|
||||
privateData String?
|
||||
|
||||
user User? @relation(fields: [userId], references: [id])
|
||||
userId Int?
|
||||
}
|
||||
|
||||
model Token {
|
||||
id Int @id @default(autoincrement())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
hashedToken String
|
||||
type String
|
||||
// See note below about TokenType enum
|
||||
// type TokenType
|
||||
expiresAt DateTime
|
||||
sentTo String
|
||||
|
||||
user User @relation(fields: [userId], references: [id])
|
||||
userId Int
|
||||
|
||||
@@unique([hashedToken, type])
|
||||
}
|
||||
|
||||
// NOTE: It's highly recommended to use an enum for the token type
|
||||
// but enums only work in Postgres.
|
||||
// See: https://blitzjs.com/docs/database-overview#switch-to-postgre-sql
|
||||
// enum TokenType {
|
||||
// RESET_PASSWORD
|
||||
// }
|
||||
15
apps/toolkit-app/db/seeds.ts
Normal file
15
apps/toolkit-app/db/seeds.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
// import db from "./index"
|
||||
|
||||
/*
|
||||
* This seed function is executed when you run `blitz db seed`.
|
||||
*
|
||||
* Probably you want to use a library like https://chancejs.com
|
||||
* to easily generate realistic data.
|
||||
*/
|
||||
const seed = async () => {
|
||||
// for (let i = 0; i < 5; i++) {
|
||||
// await db.project.create({ data: { name: "Project " + i } })
|
||||
// }
|
||||
}
|
||||
|
||||
export default seed
|
||||
0
apps/toolkit-app/integrations/.keep
Normal file
0
apps/toolkit-app/integrations/.keep
Normal file
11
apps/toolkit-app/jest.config.js
Normal file
11
apps/toolkit-app/jest.config.js
Normal file
@@ -0,0 +1,11 @@
|
||||
const nextJest = require("@blitzjs/next/jest")
|
||||
|
||||
const createJestConfig = nextJest({
|
||||
dir: "./",
|
||||
})
|
||||
|
||||
const customJestConfig = {
|
||||
testEnvironment: "jest-environment-jsdom",
|
||||
}
|
||||
|
||||
module.exports = createJestConfig(customJestConfig)
|
||||
5
apps/toolkit-app/jsconfig.json
Normal file
5
apps/toolkit-app/jsconfig.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": "."
|
||||
}
|
||||
}
|
||||
0
apps/toolkit-app/mailers/.keep
Normal file
0
apps/toolkit-app/mailers/.keep
Normal file
45
apps/toolkit-app/mailers/forgotPasswordMailer.ts
Normal file
45
apps/toolkit-app/mailers/forgotPasswordMailer.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/* TODO - You need to add a mailer integration in `integrations/` and import here.
|
||||
*
|
||||
* The integration file can be very simple. Instantiate the email client
|
||||
* and then export it. That way you can import here and anywhere else
|
||||
* and use it straight away.
|
||||
*/
|
||||
|
||||
type ResetPasswordMailer = {
|
||||
to: string
|
||||
token: string
|
||||
}
|
||||
|
||||
export function forgotPasswordMailer({ to, token }: ResetPasswordMailer) {
|
||||
// In production, set APP_ORIGIN to your production server origin
|
||||
const origin = process.env.APP_ORIGIN || process.env.BLITZ_DEV_SERVER_ORIGIN
|
||||
const resetUrl = `${origin}/reset-password?token=${token}`
|
||||
|
||||
const msg = {
|
||||
from: "TODO@example.com",
|
||||
to,
|
||||
subject: "Your Password Reset Instructions",
|
||||
html: `
|
||||
<h1>Reset Your Password</h1>
|
||||
<h3>NOTE: You must set up a production email integration in mailers/forgotPasswordMailer.ts</h3>
|
||||
|
||||
<a href="${resetUrl}">
|
||||
Click here to set a new password
|
||||
</a>
|
||||
`,
|
||||
}
|
||||
|
||||
return {
|
||||
async send() {
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
// TODO - send the production email, like this:
|
||||
// await postmark.sendEmail(msg)
|
||||
throw new Error("No production email implementation in mailers/forgotPasswordMailer")
|
||||
} else {
|
||||
// Preview email in the browser
|
||||
const previewEmail = (await import("preview-email")).default
|
||||
await previewEmail(msg)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/types/global" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
10
apps/toolkit-app/next.config.js
Normal file
10
apps/toolkit-app/next.config.js
Normal file
@@ -0,0 +1,10 @@
|
||||
const withBundleAnalyzer = require("@next/bundle-analyzer")({
|
||||
enabled: process.env.ANALYZE === "true",
|
||||
})
|
||||
const { withBlitz } = require("@blitzjs/next")
|
||||
|
||||
module.exports = withBlitz(
|
||||
withBundleAnalyzer({
|
||||
reactStrictMode: true,
|
||||
})
|
||||
)
|
||||
7
apps/toolkit-app/npmrc
Normal file
7
apps/toolkit-app/npmrc
Normal file
@@ -0,0 +1,7 @@
|
||||
save-exact=true
|
||||
legacy-peer-deps=true
|
||||
|
||||
public-hoist-pattern[]=next
|
||||
public-hoist-pattern[]=secure-password
|
||||
public-hoist-pattern[]=*jest*
|
||||
public-hoist-pattern[]=@testing-library/*
|
||||
60
apps/toolkit-app/package.json
Normal file
60
apps/toolkit-app/package.json
Normal file
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"name": "toolkit-app",
|
||||
"version": "1.0.1-alpha.16",
|
||||
"scripts": {
|
||||
"start:dev": "pnpm run prisma:start && next dev",
|
||||
"buildapp": "pnpm i && pnpm prisma generate && next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"prisma:start": "prisma generate && prisma migrate deploy",
|
||||
"prisma:studio": "prisma studio",
|
||||
"test:local": "jest"
|
||||
},
|
||||
"prisma": {
|
||||
"schema": "db/schema.prisma"
|
||||
},
|
||||
"prettier": {
|
||||
"semi": false,
|
||||
"printWidth": 100
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{js}": [
|
||||
"eslint --fix"
|
||||
]
|
||||
},
|
||||
"dependencies": {
|
||||
"@blitzjs/auth": "workspace:*",
|
||||
"@blitzjs/config": "workspace:*",
|
||||
"@blitzjs/next": "workspace:*",
|
||||
"@blitzjs/rpc": "workspace:*",
|
||||
"@hookform/resolvers": "2.8.8",
|
||||
"@prisma/client": "3.9.0",
|
||||
"blitz": "workspace:2.0.0-alpha.21",
|
||||
"next": "12.1.6-canary.17",
|
||||
"prisma": "3.9.0",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0",
|
||||
"react-hook-form": "7.29.0",
|
||||
"ts-node": "10.7.0",
|
||||
"zod": "3.10.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@next/bundle-analyzer": "12.0.8",
|
||||
"@testing-library/react": "13.0.0",
|
||||
"@testing-library/react-hooks": "7.0.2",
|
||||
"@types/jest": "27.4.1",
|
||||
"@types/node": "17.0.16",
|
||||
"@types/preview-email": "2.0.1",
|
||||
"@types/react": "17.0.43",
|
||||
"eslint": "7.32.0",
|
||||
"husky": "7.0.4",
|
||||
"jest": "27.5.1",
|
||||
"lint-staged": "12.1.7",
|
||||
"prettier": "^2.5.1",
|
||||
"prettier-plugin-prisma": "3.8.0",
|
||||
"pretty-quick": "3.1.3",
|
||||
"preview-email": "3.x",
|
||||
"typescript": "^4.5.3"
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
37
apps/toolkit-app/pages/_app.tsx
Normal file
37
apps/toolkit-app/pages/_app.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import { ErrorFallbackProps, ErrorComponent, ErrorBoundary } from "@blitzjs/next"
|
||||
import { AuthenticationError, AuthorizationError } from "blitz"
|
||||
import type { AppProps } from "next/app"
|
||||
import React, { Suspense } from "react"
|
||||
import { withBlitz } from "app/blitz-client"
|
||||
|
||||
function RootErrorFallback({ error }: ErrorFallbackProps) {
|
||||
if (error instanceof AuthenticationError) {
|
||||
return <div>Error: You are not authenticated</div>
|
||||
} else if (error instanceof AuthorizationError) {
|
||||
return (
|
||||
<ErrorComponent
|
||||
statusCode={error.statusCode}
|
||||
title="Sorry, you are not authorized to access this"
|
||||
/>
|
||||
)
|
||||
} else {
|
||||
return (
|
||||
<ErrorComponent
|
||||
statusCode={(error as any)?.statusCode || 400}
|
||||
title={error.message || error.name}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function MyApp({ Component, pageProps }: AppProps) {
|
||||
return (
|
||||
<ErrorBoundary FallbackComponent={RootErrorFallback}>
|
||||
<Suspense fallback="Loading...">
|
||||
<Component {...pageProps} />
|
||||
</Suspense>
|
||||
</ErrorBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
export default withBlitz(MyApp)
|
||||
4
apps/toolkit-app/pages/api/rpc/[[...blitz]].ts
Normal file
4
apps/toolkit-app/pages/api/rpc/[[...blitz]].ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { rpcHandler } from "@blitzjs/rpc"
|
||||
import { api } from "app/blitz-server"
|
||||
|
||||
export default api(rpcHandler({ onError: console.log }))
|
||||
@@ -1,15 +1,15 @@
|
||||
import { BlitzPage, useMutation } from "blitz"
|
||||
import Layout from "app/core/layouts/Layout"
|
||||
import { LabeledTextField } from "app/core/components/LabeledTextField"
|
||||
import { Form, FORM_ERROR } from "app/core/components/Form"
|
||||
import { ForgotPassword } from "app/auth/validations"
|
||||
import forgotPassword from "app/auth/mutations/forgotPassword"
|
||||
import { useMutation } from "@blitzjs/rpc"
|
||||
|
||||
const ForgotPasswordPage: BlitzPage = () => {
|
||||
const ForgotPasswordPage = () => {
|
||||
const [forgotPasswordMutation, { isSuccess }] = useMutation(forgotPassword)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Layout title="Forgot Your Password?">
|
||||
<h1>Forgot your password?</h1>
|
||||
|
||||
{isSuccess ? (
|
||||
@@ -38,11 +38,8 @@ const ForgotPasswordPage: BlitzPage = () => {
|
||||
<LabeledTextField name="email" label="Email" placeholder="Email" />
|
||||
</Form>
|
||||
)}
|
||||
</div>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
ForgotPasswordPage.redirectAuthenticatedTo = "/"
|
||||
ForgotPasswordPage.getLayout = (page) => <Layout title="Forgot Your Password?">{page}</Layout>
|
||||
|
||||
export default ForgotPasswordPage
|
||||
@@ -1,23 +1,20 @@
|
||||
import { useRouter, BlitzPage } from "blitz"
|
||||
import Layout from "app/core/layouts/Layout"
|
||||
import { LoginForm } from "app/auth/components/LoginForm"
|
||||
import { useRouter } from "next/router"
|
||||
|
||||
const LoginPage: BlitzPage = () => {
|
||||
const LoginPage = () => {
|
||||
const router = useRouter()
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Layout title="Log In">
|
||||
<LoginForm
|
||||
onSuccess={(_user) => {
|
||||
const next = router.query.next ? decodeURIComponent(router.query.next as string) : "/"
|
||||
router.push(next)
|
||||
return router.push(next)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
LoginPage.redirectAuthenticatedTo = "/"
|
||||
LoginPage.getLayout = (page) => <Layout title="Log In">{page}</Layout>
|
||||
|
||||
export default LoginPage
|
||||
@@ -1,18 +1,16 @@
|
||||
import { useRouter, BlitzPage, Routes } from "blitz"
|
||||
import { useRouter } from "next/router"
|
||||
import Layout from "app/core/layouts/Layout"
|
||||
import { SignupForm } from "app/auth/components/SignupForm"
|
||||
import { Routes } from "@blitzjs/next"
|
||||
|
||||
const SignupPage: BlitzPage = () => {
|
||||
const SignupPage = () => {
|
||||
const router = useRouter()
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Layout title="Sign Up">
|
||||
<SignupForm onSuccess={() => router.push(Routes.Home())} />
|
||||
</div>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
SignupPage.redirectAuthenticatedTo = "/"
|
||||
SignupPage.getLayout = (page) => <Layout title="Sign Up">{page}</Layout>
|
||||
|
||||
export default SignupPage
|
||||
274
apps/toolkit-app/pages/index.tsx
Normal file
274
apps/toolkit-app/pages/index.tsx
Normal file
@@ -0,0 +1,274 @@
|
||||
import { Suspense } from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import Layout from "app/core/layouts/Layout"
|
||||
import { useCurrentUser } from "app/core/hooks/useCurrentUser"
|
||||
import logout from "app/auth/mutations/logout"
|
||||
import logo from "public/logo.png"
|
||||
import { useMutation } from "@blitzjs/rpc"
|
||||
import { Routes } from "@blitzjs/next"
|
||||
|
||||
/*
|
||||
* This file is just for a pleasant getting started page for your new app.
|
||||
* You can delete everything in here and start from scratch if you like.
|
||||
*/
|
||||
|
||||
const UserInfo = () => {
|
||||
const currentUser = useCurrentUser()
|
||||
const [logoutMutation] = useMutation(logout)
|
||||
|
||||
if (currentUser) {
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
className="button small"
|
||||
onClick={async () => {
|
||||
await logoutMutation()
|
||||
}}
|
||||
>
|
||||
Logout
|
||||
</button>
|
||||
<div>
|
||||
User id: <code>{currentUser.id}</code>
|
||||
<br />
|
||||
User role: <code>{currentUser.role}</code>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
} else {
|
||||
return (
|
||||
<>
|
||||
<Link href={Routes.SignupPage()} passHref>
|
||||
<a className="button small">
|
||||
<strong>Sign Up</strong>
|
||||
</a>
|
||||
</Link>
|
||||
<Link href={Routes.LoginPage()} passHref>
|
||||
<a className="button small">
|
||||
<strong>Login</strong>
|
||||
</a>
|
||||
</Link>
|
||||
</>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const Home = () => {
|
||||
return (
|
||||
<Layout title="Home">
|
||||
<div className="container">
|
||||
<main>
|
||||
<div className="logo">
|
||||
<Image src={`${logo.src}`} alt="blitzjs" width="256px" height="118px" layout="fixed" />
|
||||
</div>
|
||||
<p>
|
||||
<strong>Congrats!</strong> Your app is ready, including user sign-up and log-in.
|
||||
</p>
|
||||
<div className="buttons" style={{ marginTop: "1rem", marginBottom: "1rem" }}>
|
||||
<Suspense fallback="Loading...">
|
||||
<UserInfo />
|
||||
</Suspense>
|
||||
</div>
|
||||
<p>
|
||||
<strong>
|
||||
To add a new model to your app, <br />
|
||||
run the following in your terminal:
|
||||
</strong>
|
||||
</p>
|
||||
<pre>
|
||||
<code>blitz generate all project name:string</code>
|
||||
</pre>
|
||||
<div style={{ marginBottom: "1rem" }}>(And select Yes to run prisma migrate)</div>
|
||||
<div>
|
||||
<p>
|
||||
Then <strong>restart the server</strong>
|
||||
</p>
|
||||
<pre>
|
||||
<code>Ctrl + c</code>
|
||||
</pre>
|
||||
<pre>
|
||||
<code>blitz dev</code>
|
||||
</pre>
|
||||
<p>
|
||||
and go to{" "}
|
||||
<Link href="/projects">
|
||||
<a>/projects</a>
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
<div className="buttons" style={{ marginTop: "5rem" }}>
|
||||
<a
|
||||
className="button"
|
||||
href="https://blitzjs.com/docs/getting-started?utm_source=blitz-new&utm_medium=app-template&utm_campaign=blitz-new"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Documentation
|
||||
</a>
|
||||
<a
|
||||
className="button-outline"
|
||||
href="https://github.com/blitz-js/blitz"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Github Repo
|
||||
</a>
|
||||
<a
|
||||
className="button-outline"
|
||||
href="https://discord.blitzjs.com"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Discord Community
|
||||
</a>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<a
|
||||
href="https://blitzjs.com?utm_source=blitz-new&utm_medium=app-template&utm_campaign=blitz-new"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Powered by Blitz.js
|
||||
</a>
|
||||
</footer>
|
||||
|
||||
<style jsx global>{`
|
||||
@import url("https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;700&display=swap");
|
||||
|
||||
html,
|
||||
body {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-family: "Libre Franklin", -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
|
||||
Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
|
||||
}
|
||||
|
||||
* {
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.container {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
main {
|
||||
padding: 5rem 0;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
main p {
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
p {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
footer {
|
||||
width: 100%;
|
||||
height: 60px;
|
||||
border-top: 1px solid #eaeaea;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background-color: #45009d;
|
||||
}
|
||||
|
||||
footer a {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
footer a {
|
||||
color: #f4f4f4;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.logo {
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.logo img {
|
||||
width: 300px;
|
||||
}
|
||||
|
||||
.buttons {
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
grid-gap: 0.5rem;
|
||||
}
|
||||
.button {
|
||||
font-size: 1rem;
|
||||
background-color: #6700eb;
|
||||
padding: 1rem 2rem;
|
||||
color: #f4f4f4;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.button.small {
|
||||
padding: 0.5rem 1rem;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
background-color: #45009d;
|
||||
}
|
||||
|
||||
.button-outline {
|
||||
border: 2px solid #6700eb;
|
||||
padding: 1rem 2rem;
|
||||
color: #6700eb;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.button-outline:hover {
|
||||
border-color: #45009d;
|
||||
color: #45009d;
|
||||
}
|
||||
|
||||
pre {
|
||||
background: #fafafa;
|
||||
border-radius: 5px;
|
||||
padding: 0.75rem;
|
||||
text-align: center;
|
||||
}
|
||||
code {
|
||||
font-size: 0.9rem;
|
||||
font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono,
|
||||
Bitstream Vera Sans Mono, Courier New, monospace;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
|
||||
max-width: 800px;
|
||||
margin-top: 3rem;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.grid {
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
export default Home
|
||||
BIN
apps/toolkit-app/public/favicon.ico
Executable file
BIN
apps/toolkit-app/public/favicon.ico
Executable file
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
BIN
apps/toolkit-app/public/logo.png
Normal file
BIN
apps/toolkit-app/public/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 33 KiB |
4
apps/toolkit-app/test/setup.ts
Normal file
4
apps/toolkit-app/test/setup.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
// This is the jest 'setupFilesAfterEnv' setup file
|
||||
// It's a good place to set globals, add global before/after hooks, etc
|
||||
|
||||
export {} // so TS doesn't complain
|
||||
24
apps/toolkit-app/tsconfig.json
Normal file
24
apps/toolkit-app/tsconfig.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"baseUrl": ".",
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": false,
|
||||
"strictNullChecks": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noEmit": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"incremental": true,
|
||||
"tsBuildInfoFile": ".tsbuildinfo"
|
||||
},
|
||||
"exclude": ["node_modules", "**/*.e2e.ts", "cypress"],
|
||||
"include": ["blitz-env.d.ts", "**/*.ts", "**/*.tsx", "types"]
|
||||
}
|
||||
15
apps/toolkit-app/types.ts
Normal file
15
apps/toolkit-app/types.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { SimpleRolesIsAuthorized } from "@blitzjs/auth"
|
||||
import { User } from "db"
|
||||
|
||||
export type Role = "ADMIN" | "USER"
|
||||
|
||||
declare module "@blitzjs/auth" {
|
||||
export interface Session {
|
||||
isAuthorized: SimpleRolesIsAuthorized<Role>
|
||||
PublicData: {
|
||||
userId: User["id"]
|
||||
role: Role
|
||||
views?: number
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import {AuthClientPlugin} from "@blitzjs/auth"
|
||||
import {setupClient} from "@blitzjs/next"
|
||||
import {setupBlitzClient} from "@blitzjs/next"
|
||||
import {BlitzRpcPlugin} from "@blitzjs/rpc"
|
||||
|
||||
const {withBlitz} = setupClient({
|
||||
const {withBlitz} = setupBlitzClient({
|
||||
plugins: [
|
||||
AuthClientPlugin({
|
||||
cookiePrefix: "webapp-cookie-prefix",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {setupBlitz} from "@blitzjs/next"
|
||||
import {setupBlitzServer} from "@blitzjs/next"
|
||||
import {AuthServerPlugin, PrismaStorage} from "@blitzjs/auth"
|
||||
import {prisma as db} from "../prisma/index"
|
||||
import {simpleRolesIsAuthorized} from "@blitzjs/auth"
|
||||
|
||||
const {gSSP, gSP, api} = setupBlitz({
|
||||
const {gSSP, gSP, api} = setupBlitzServer({
|
||||
plugins: [
|
||||
AuthServerPlugin({
|
||||
cookiePrefix: "webapp-cookie-prefix",
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
"@types/jest": "27.4.1",
|
||||
"blitz": "workspace:*",
|
||||
"jest": "27.5.1",
|
||||
"next": "12.1.1",
|
||||
"next": "12.1.6-canary.17",
|
||||
"prisma": "3.9.0",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0",
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import {gSP} from "app/blitz-server"
|
||||
|
||||
export const getStaticProps = gSP(async ({ctx}) => {
|
||||
export const getStaticProps = gSP<{data: {test: string}}>(async ({ctx}) => {
|
||||
return {
|
||||
props: {
|
||||
data: {
|
||||
// userId: ctx?.session.userId,
|
||||
// session: {
|
||||
// id: session.userId,
|
||||
// publicData: session.$publicData,
|
||||
// },
|
||||
test: "hello",
|
||||
date: new Date(),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ export const getServerSideProps = gSSP<Props>(async ({ctx}) => {
|
||||
props: {
|
||||
userId: session.userId,
|
||||
publicData: session.$publicData,
|
||||
publishedAt: new Date(0),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {AuthClientPlugin} from "@blitzjs/auth"
|
||||
import {setupClient} from "@blitzjs/next"
|
||||
import {setupBlitzClient} from "@blitzjs/next"
|
||||
|
||||
const {withBlitz} = setupClient({
|
||||
const {withBlitz} = setupBlitzClient({
|
||||
plugins: [
|
||||
AuthClientPlugin({
|
||||
cookiePrefix: "auth-tests-cookie-prefix",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {setupBlitz} from "@blitzjs/next"
|
||||
import {setupBlitzServer} from "@blitzjs/next"
|
||||
import {AuthServerPlugin, PrismaStorage} from "@blitzjs/auth"
|
||||
import {simpleRolesIsAuthorized} from "@blitzjs/auth"
|
||||
import {prisma as db} from "../prisma/index"
|
||||
|
||||
const {gSSP, gSP, api} = setupBlitz({
|
||||
const {gSSP, gSP, api} = setupBlitzServer({
|
||||
plugins: [
|
||||
AuthServerPlugin({
|
||||
cookiePrefix: "auth-tests-cookie-prefix",
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
"@prisma/client": "3.9.0",
|
||||
"blitz": "workspace:*",
|
||||
"lowdb": "3.0.0",
|
||||
"next": "12.1.1",
|
||||
"next": "12.1.6-canary.17",
|
||||
"prisma": "3.9.0",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0"
|
||||
|
||||
1
integration-tests/qm/.eslintrc.js
Normal file
1
integration-tests/qm/.eslintrc.js
Normal file
@@ -0,0 +1 @@
|
||||
module.exports = require("@blitzjs/config/eslint")
|
||||
3
integration-tests/qm/.gitignore
vendored
Normal file
3
integration-tests/qm/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
node_modules
|
||||
# Keep environment variables out of version control
|
||||
*.sqlite
|
||||
5
integration-tests/qm/next-env.d.ts
vendored
Normal file
5
integration-tests/qm/next-env.d.ts
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/basic-features/typescript for more information.
|
||||
4
integration-tests/qm/next.config.js
Normal file
4
integration-tests/qm/next.config.js
Normal file
@@ -0,0 +1,4 @@
|
||||
const {withBlitz} = require("@blitzjs/next")
|
||||
module.exports = withBlitz({
|
||||
// update me
|
||||
})
|
||||
34
integration-tests/qm/package.json
Normal file
34
integration-tests/qm/package.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "test-qm",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"test-watch": "vitest",
|
||||
"clean": "rm -rf .turbo && rm -rf node_modules"
|
||||
},
|
||||
"dependencies": {
|
||||
"@blitzjs/auth": "workspace:*",
|
||||
"@blitzjs/config": "workspace:*",
|
||||
"@blitzjs/next": "workspace:*",
|
||||
"@blitzjs/rpc": "workspace:*",
|
||||
"@prisma/client": "3.9.0",
|
||||
"blitz": "workspace:*",
|
||||
"next": "12.1.6-canary.17",
|
||||
"prisma": "3.9.0",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0",
|
||||
"react-query": "3.21.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/react": "13.0.0",
|
||||
"@types/react": "17.0.43",
|
||||
"@vitejs/plugin-react": "1.3.0",
|
||||
"delay": "5.0.0",
|
||||
"eslint": "7.32.0",
|
||||
"eslint-config-next": "latest",
|
||||
"eslint-plugin-testing-library": "5.0.1",
|
||||
"jsdom": "^19.0.0",
|
||||
"typescript": "^4.5.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// Vitest Snapshot v1
|
||||
|
||||
exports[`useMutation > useMutation calls the resolver with the argument > shouldn't work with query function 1`] = `"\\"useMutation\\" was expected to be called with a mutation but was called with a \\"query\\""`;
|
||||
|
||||
exports[`useMutation > useMutation calls the resolver with the argument > shouldn't work with regular functions 1`] = `"Either the file path to your resolver is incorrect (must be in a \\"queries\\" or \\"mutations\\" folder that isn't nested inside \\"pages\\" or \\"api\\") or you are trying to use Blitz's useQuery to fetch from third-party APIs (to do that, import useQuery directly from \\"react-query\\")"`;
|
||||
@@ -0,0 +1,5 @@
|
||||
// Vitest Snapshot v1
|
||||
|
||||
exports[`useQuery > a "query" that converts the string parameter to uppercase > shouldn't work with mutation function 1`] = `"Cannot read properties of null (reading 'isReady')"`;
|
||||
|
||||
exports[`useQuery > a "query" that converts the string parameter to uppercase > shouldn't work with regular functions 1`] = `"Cannot read properties of null (reading 'isReady')"`;
|
||||
55
integration-tests/qm/test/use-mutation.test.tsx
Normal file
55
integration-tests/qm/test/use-mutation.test.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import {describe, it, expect, beforeAll, vi} from "vitest"
|
||||
import {act, screen} from "@testing-library/react"
|
||||
import {useMutation} from "@blitzjs/rpc"
|
||||
import React from "react"
|
||||
import {buildMutationRpc, buildQueryRpc, render} from "../../utils/blitz-test-utils"
|
||||
|
||||
beforeAll(() => {
|
||||
globalThis.__BLITZ_SESSION_COOKIE_PREFIX = "qm-test-cookie-prefix"
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
})
|
||||
|
||||
describe("useMutation", () => {
|
||||
const setupHook = (resolver: (...args: any) => Promise<any>): [{mutate?: Function}, Function] => {
|
||||
let res = {}
|
||||
|
||||
function TestHarness() {
|
||||
const [mutate, {isSuccess}] = useMutation(resolver)
|
||||
|
||||
Object.assign(res, {mutate})
|
||||
return <div id="harness">{isSuccess ? "Sent" : "Waiting"}</div>
|
||||
}
|
||||
|
||||
const ui = () => <TestHarness />
|
||||
|
||||
const {rerender} = render(ui())
|
||||
return [res, () => rerender(ui())]
|
||||
}
|
||||
|
||||
describe("useMutation calls the resolver with the argument", () => {
|
||||
// eslint-disable-next-line require-await
|
||||
const mutateFn = vi.fn()
|
||||
it("should work with Blitz mutations", async () => {
|
||||
const [res] = setupHook(buildMutationRpc(mutateFn))
|
||||
await act(async () => {
|
||||
await res.mutate!("data")
|
||||
})
|
||||
|
||||
await screen.findByText("Sent")
|
||||
expect(mutateFn).toHaveBeenCalledTimes(1)
|
||||
expect(mutateFn).toHaveBeenCalledWith("data", {fromQueryHook: true})
|
||||
})
|
||||
|
||||
it("shouldn't work with regular functions", () => {
|
||||
console.error = vi.fn()
|
||||
expect(() => setupHook(mutateFn)).toThrowErrorMatchingSnapshot()
|
||||
})
|
||||
|
||||
it("shouldn't work with query function", () => {
|
||||
console.error = vi.fn()
|
||||
const mutationFn = vi.fn()
|
||||
|
||||
expect(() => setupHook(buildQueryRpc(mutationFn))).toThrowErrorMatchingSnapshot()
|
||||
})
|
||||
})
|
||||
})
|
||||
166
integration-tests/qm/test/use-query.test.tsx
Normal file
166
integration-tests/qm/test/use-query.test.tsx
Normal file
@@ -0,0 +1,166 @@
|
||||
import {describe, it, expect, beforeAll, vi} from "vitest"
|
||||
import {act, screen, waitForElementToBeRemoved, waitFor} from "@testing-library/react"
|
||||
import {useQuery, useInfiniteQuery} from "@blitzjs/rpc"
|
||||
import React from "react"
|
||||
import delay from "delay"
|
||||
import {buildMutationRpc, buildQueryRpc, render} from "../../utils/blitz-test-utils"
|
||||
|
||||
describe("useQuery", () => {
|
||||
it("Placeholder", async () => {
|
||||
console.log("placeholder")
|
||||
})
|
||||
})
|
||||
// beforeAll(() => {
|
||||
// globalThis.__BLITZ_SESSION_COOKIE_PREFIX = "qm-test-cookie-prefix"
|
||||
// globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
// })
|
||||
|
||||
// describe("useQuery", () => {
|
||||
// const setupHook = (
|
||||
// params: any,
|
||||
// queryFn: (...args: any) => any,
|
||||
// options: Parameters<typeof useQuery>[2] = {} as any,
|
||||
// ): [{data?: any; setQueryData?: any}, Function] => {
|
||||
// let res = {}
|
||||
// function TestHarness() {
|
||||
// const [data, {setQueryData}] = useQuery(queryFn, params, {
|
||||
// suspense: true,
|
||||
// ...options,
|
||||
// } as any)
|
||||
// Object.assign(res, {data, setQueryData})
|
||||
// return (
|
||||
// <div id="harness">
|
||||
// <span>{data ? "Ready" : "No data"}</span>
|
||||
// <span>{data}</span>
|
||||
// </div>
|
||||
// )
|
||||
// }
|
||||
|
||||
// const ui = () => (
|
||||
// <React.Suspense fallback="Loading...">
|
||||
// <TestHarness />
|
||||
// </React.Suspense>
|
||||
// )
|
||||
|
||||
// const {rerender} = render(ui())
|
||||
// return [res, () => rerender(ui())]
|
||||
// }
|
||||
|
||||
// describe('a "query" that converts the string parameter to uppercase', () => {
|
||||
// const upcase = async (args: string) => {
|
||||
// await delay(1000)
|
||||
// return args.toUpperCase()
|
||||
// }
|
||||
// it("should work with Blitz queries", async () => {
|
||||
// const [res] = setupHook("test", buildQueryRpc(upcase))
|
||||
// await waitForElementToBeRemoved(() => screen.getByText("Loading..."))
|
||||
// await act(async () => {
|
||||
// await screen.findByText("Ready")
|
||||
// expect(res.data).toBe("TEST")
|
||||
// })
|
||||
// })
|
||||
|
||||
// it("should be able to change the data with setQueryData", async () => {
|
||||
// const [res] = setupHook("test", buildQueryRpc(upcase))
|
||||
// await waitForElementToBeRemoved(() => screen.getByText("Loading..."))
|
||||
// await act(async () => {
|
||||
// await screen.findByText("Ready")
|
||||
// expect(res.data).toBe("TEST")
|
||||
// res.setQueryData((p: string) => p.substr(1, 2), {refetch: false})
|
||||
// await waitFor(() => screen.getByText("ES"))
|
||||
// })
|
||||
// })
|
||||
|
||||
// it("shouldn't work with regular functions", () => {
|
||||
// console.error = vi.fn()
|
||||
// expect(() => setupHook("test", upcase)).toThrowErrorMatchingSnapshot()
|
||||
// })
|
||||
|
||||
// it("shouldn't work with mutation function", () => {
|
||||
// console.error = vi.fn()
|
||||
// expect(() => setupHook("test", buildMutationRpc(upcase))).toThrowErrorMatchingSnapshot()
|
||||
// })
|
||||
|
||||
// it("suspense disabled if enabled is false", async () => {
|
||||
// setupHook("test", buildQueryRpc(upcase), {enabled: false})
|
||||
// await screen.findByText("No data")
|
||||
// })
|
||||
|
||||
// it("suspense disabled if enabled is undefined", async () => {
|
||||
// setupHook("test", buildQueryRpc(upcase), {enabled: undefined})
|
||||
// await screen.findByText("No data")
|
||||
// })
|
||||
|
||||
// it("suspense disabled if enabled is false and suspense set", async () => {
|
||||
// setupHook("test", buildQueryRpc(upcase), {
|
||||
// enabled: false,
|
||||
// suspense: true,
|
||||
// })
|
||||
// await screen.findByText("No data")
|
||||
// })
|
||||
// })
|
||||
|
||||
// // it("works with options other than enabled & suspense without type error", () => {
|
||||
// // const queryFn = ((() => true) as unknown) as () => Promise<boolean>
|
||||
// // useQuery(queryFn, undefined, {refetchInterval: 10000})
|
||||
// // })
|
||||
// })
|
||||
|
||||
// describe("useInfiniteQuery", () => {
|
||||
// const setupHook = (
|
||||
// params: (arg?: any) => any,
|
||||
// queryFn: (...args: any) => any,
|
||||
// ): [{data?: any; setQueryData?: any}, Function] => {
|
||||
// let res = {}
|
||||
// function TestHarness() {
|
||||
// // TODO - fix typing
|
||||
// //@ts-ignore
|
||||
// const [groupedData] = useInfiniteQuery(queryFn, params, {
|
||||
// suspense: true,
|
||||
// getNextPageParam: () => {},
|
||||
// })
|
||||
// Object.assign(res, {groupedData})
|
||||
// return (
|
||||
// <div id="harness">
|
||||
// <span>{groupedData ? "Ready" : "No data"}</span>
|
||||
// <div>
|
||||
// {groupedData.map((data: any, i) => (
|
||||
// <div key={i}>{data}</div>
|
||||
// ))}
|
||||
// </div>
|
||||
// </div>
|
||||
// )
|
||||
// }
|
||||
|
||||
// const ui = () => (
|
||||
// <React.Suspense fallback="Loading...">
|
||||
// <TestHarness />
|
||||
// </React.Suspense>
|
||||
// )
|
||||
|
||||
// const {rerender} = render(ui())
|
||||
// return [res, () => rerender(ui())]
|
||||
// }
|
||||
|
||||
// const getItems = ({id}: {id: number}) => {
|
||||
// if (id === 1) {
|
||||
// return "item1"
|
||||
// } else if (id === 2) {
|
||||
// return "item2"
|
||||
// } else {
|
||||
// throw new Error("No item for this id")
|
||||
// }
|
||||
// }
|
||||
// it("should work", async () => {
|
||||
// setupHook(() => ({id: 1}), buildQueryRpc(getItems))
|
||||
// await waitForElementToBeRemoved(() => screen.getByText("Loading..."))
|
||||
// await act(async () => {
|
||||
// await screen.findByText("item1")
|
||||
// })
|
||||
|
||||
// setupHook(() => ({id: 2}), buildQueryRpc(getItems))
|
||||
// await act(async () => {
|
||||
// await screen.findByText("item2")
|
||||
// })
|
||||
// })
|
||||
// })
|
||||
13
integration-tests/qm/tsconfig.json
Normal file
13
integration-tests/qm/tsconfig.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "@blitzjs/config/tsconfig.nextjs.json",
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "../utils/blitz-test-utils.tsx"],
|
||||
"compilerOptions": {
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"paths": {
|
||||
"react": ["./node_modules/@types/react"]
|
||||
}
|
||||
},
|
||||
"exclude": ["node_modules"],
|
||||
"baseUrl": "."
|
||||
}
|
||||
12
integration-tests/qm/vitest.config.ts
Normal file
12
integration-tests/qm/vitest.config.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
/// <reference types="vitest" />
|
||||
|
||||
import { defineConfig } from 'vitest/config'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
},
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
const {withBlitz} = require("@blitzjs/next")
|
||||
module.exports = withBlitz({
|
||||
// update me
|
||||
target: 'experimental-serverless-trace',
|
||||
})
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
"@blitzjs/next": "workspace:*",
|
||||
"@blitzjs/rpc": "workspace:*",
|
||||
"blitz": "workspace:*",
|
||||
"next": "12.1.1",
|
||||
"next": "12.1.6-canary.17",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0"
|
||||
},
|
||||
|
||||
123
integration-tests/utils/blitz-test-utils.tsx
Normal file
123
integration-tests/utils/blitz-test-utils.tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
import {render as defaultRender} from "@testing-library/react"
|
||||
import {NextRouter} from "next/router"
|
||||
import {vi} from "vitest"
|
||||
import {QueryClient, QueryClientProvider} from "react-query"
|
||||
import React from "react"
|
||||
import {BlitzRpcPlugin} from "@blitzjs/rpc"
|
||||
|
||||
const mockRouter: NextRouter = {
|
||||
basePath: "",
|
||||
pathname: "/",
|
||||
route: "/",
|
||||
asPath: "/",
|
||||
query: {},
|
||||
isReady: true,
|
||||
isLocaleDomain: false,
|
||||
isPreview: false,
|
||||
push: vi.fn(),
|
||||
replace: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
back: vi.fn(),
|
||||
prefetch: vi.fn(),
|
||||
beforePopState: vi.fn(),
|
||||
events: {
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
emit: vi.fn(),
|
||||
},
|
||||
isFallback: false,
|
||||
}
|
||||
|
||||
type DefaultParams = Parameters<typeof defaultRender>
|
||||
type RenderUI = DefaultParams[0]
|
||||
type RenderOptions = DefaultParams[1] & {
|
||||
router?: Partial<NextRouter>
|
||||
}
|
||||
export type BlitzProviderProps = {
|
||||
client?: QueryClient
|
||||
contextSharing?: boolean
|
||||
}
|
||||
|
||||
const BlitzProvider = ({
|
||||
client,
|
||||
contextSharing = false,
|
||||
children,
|
||||
}: BlitzProviderProps & {children: JSX.Element}) => {
|
||||
if (globalThis.queryClient) {
|
||||
return (
|
||||
<QueryClientProvider
|
||||
client={client || globalThis.queryClient}
|
||||
contextSharing={contextSharing}
|
||||
>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
return children
|
||||
}
|
||||
export const RouterContext = React.createContext(null as any)
|
||||
RouterContext.displayName = "RouterContext"
|
||||
const compose =
|
||||
(...rest) =>
|
||||
(x: React.ComponentType<any>) =>
|
||||
rest.reduceRight((y, f) => f(y), x)
|
||||
|
||||
const BlitzWrapper = ({plugins, children}) => {
|
||||
const providers = plugins.reduce((acc, plugin) => {
|
||||
return plugin.withProvider ? acc.concat(plugin.withProvider) : acc
|
||||
}, [])
|
||||
const withPlugins = compose(...providers)
|
||||
const component = React.useMemo(() => withPlugins(children), [children])
|
||||
|
||||
return (
|
||||
<BlitzProvider>
|
||||
<RouterContext.Provider value={{...mockRouter}}>{component}</RouterContext.Provider>
|
||||
</BlitzProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export function render(ui: RenderUI, {wrapper, router, ...options}: RenderOptions = {}) {
|
||||
if (!wrapper) {
|
||||
wrapper = ({children}) => {
|
||||
return (
|
||||
<BlitzWrapper
|
||||
plugins={[
|
||||
BlitzRpcPlugin({
|
||||
reactQueryOptions: {
|
||||
queries: {
|
||||
staleTime: 7000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
]}
|
||||
>
|
||||
{children}
|
||||
</BlitzWrapper>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return defaultRender(ui, {wrapper, ...options})
|
||||
}
|
||||
|
||||
// This enhance fn does what buildRpcFunction does during build time
|
||||
export function buildQueryRpc(fn: any) {
|
||||
const newFn = (...args: any) => {
|
||||
const [data, ...rest] = args
|
||||
return fn(data, ...rest)
|
||||
}
|
||||
newFn._isRpcClient = true
|
||||
newFn._resolverType = "query"
|
||||
newFn._routePath = "/api/test/url/" + Math.random()
|
||||
return newFn
|
||||
}
|
||||
|
||||
// This enhance fn does what buildRpcFunction does during build time
|
||||
export function buildMutationRpc(fn: any) {
|
||||
const newFn = (...args: any) => fn(...args)
|
||||
newFn._isRpcClient = true
|
||||
newFn._resolverType = "mutation"
|
||||
newFn._routePath = "/api/test/url"
|
||||
return newFn
|
||||
}
|
||||
@@ -12,6 +12,8 @@ export function waitFor(millis) {
|
||||
return new Promise((resolve) => setTimeout(resolve, millis))
|
||||
}
|
||||
|
||||
export {By}
|
||||
|
||||
const {
|
||||
BROWSER_NAME: browserName = "chrome",
|
||||
BROWSERSTACK,
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"devDependencies": {
|
||||
"@blitzjs/config": "workspace: *",
|
||||
"@blitzjs/rpc": "workspace: *",
|
||||
"@testing-library/react": "13.0.0",
|
||||
"@types/express": "4.17.13",
|
||||
"@types/fs-extra": "9.0.13",
|
||||
"@types/node-fetch": "2.6.1",
|
||||
@@ -16,6 +19,9 @@
|
||||
"fs-extra": "10.0.1",
|
||||
"get-port": "6.1.2",
|
||||
"node-fetch": "3.2.3",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0",
|
||||
"react-query": "3.21.1",
|
||||
"rimraf": "3.0.2",
|
||||
"selenium-webdriver": "4.1.1",
|
||||
"tree-kill": "1.2.2",
|
||||
|
||||
13
integration-tests/utils/tsconfig.json
Normal file
13
integration-tests/utils/tsconfig.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "@blitzjs/config/tsconfig.nextjs.json",
|
||||
"include": ["*.ts", "*.tsx"],
|
||||
"compilerOptions": {
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"paths": {
|
||||
"react": ["./node_modules/@types/react"]
|
||||
}
|
||||
},
|
||||
"exclude": ["node_modules"],
|
||||
"baseUrl": "."
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user