Compare commits
5 commits
master
...
add-deprec
Author | SHA1 | Date | |
---|---|---|---|
|
2694d7ad06 | ||
|
e6b2e57db8 | ||
|
84350bfb0f | ||
|
c10ac894b8 | ||
|
4f83f53a57 |
727 changed files with 30706 additions and 51875 deletions
|
@ -1,2 +0,0 @@
|
||||||
[codespell]
|
|
||||||
ignore-words-list = crate
|
|
40
.github/dependabot.yml
vendored
40
.github/dependabot.yml
vendored
|
@ -1,16 +1,34 @@
|
||||||
version: 2
|
version: 2
|
||||||
updates:
|
updates:
|
||||||
- package-ecosystem: cargo
|
- package-ecosystem: cargo
|
||||||
directory: /
|
directory: "/"
|
||||||
schedule:
|
|
||||||
interval: daily
|
|
||||||
|
|
||||||
- package-ecosystem: github-actions
|
|
||||||
directory: /
|
|
||||||
schedule:
|
|
||||||
interval: daily
|
|
||||||
|
|
||||||
- package-ecosystem: npm
|
|
||||||
directory: /juniper/
|
|
||||||
schedule:
|
schedule:
|
||||||
interval: daily
|
interval: daily
|
||||||
|
open-pull-requests-limit: 10
|
||||||
|
ignore:
|
||||||
|
- dependency-name: warp
|
||||||
|
versions:
|
||||||
|
- 0.3.0
|
||||||
|
- 0.3.1
|
||||||
|
- dependency-name: tokio
|
||||||
|
versions:
|
||||||
|
- 1.1.0
|
||||||
|
- 1.2.0
|
||||||
|
- 1.3.0
|
||||||
|
- 1.4.0
|
||||||
|
- dependency-name: actix
|
||||||
|
versions:
|
||||||
|
- 0.11.0
|
||||||
|
- dependency-name: actix-rt
|
||||||
|
versions:
|
||||||
|
- 2.0.0
|
||||||
|
- 2.1.0
|
||||||
|
- dependency-name: bytes
|
||||||
|
versions:
|
||||||
|
- 1.0.0
|
||||||
|
- dependency-name: hyper
|
||||||
|
versions:
|
||||||
|
- 0.14.1
|
||||||
|
- dependency-name: rand
|
||||||
|
versions:
|
||||||
|
- 0.8.0
|
||||||
|
|
57
.github/workflows/book.yml
vendored
Normal file
57
.github/workflows/book.yml
vendored
Normal file
|
@ -0,0 +1,57 @@
|
||||||
|
name: Book
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- 'docs/book/**'
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- 'docs/book/**'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
tests:
|
||||||
|
name: Test code examples
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install rust
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- name: Test via skeptic
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: test
|
||||||
|
args: --manifest-path docs/book/tests/Cargo.toml
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
name: Deploy book on gh-pages
|
||||||
|
needs: [tests]
|
||||||
|
if: github.ref == 'refs/heads/master'
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install mdBook
|
||||||
|
uses: peaceiris/actions-mdbook@v1
|
||||||
|
|
||||||
|
- name: Render book
|
||||||
|
run: |
|
||||||
|
mdbook build -d gh-pages/master docs/book
|
||||||
|
|
||||||
|
- name: Deploy
|
||||||
|
uses: peaceiris/actions-gh-pages@v3
|
||||||
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
keepFiles: true
|
||||||
|
publish_dir: docs/book/gh-pages
|
486
.github/workflows/ci.yml
vendored
486
.github/workflows/ci.yml
vendored
|
@ -1,429 +1,151 @@
|
||||||
name: CI
|
name: CI
|
||||||
|
|
||||||
on:
|
on: [pull_request, push]
|
||||||
push:
|
|
||||||
branches: ["master"]
|
|
||||||
tags: ["juniper*"]
|
|
||||||
pull_request:
|
|
||||||
branches: ["master"]
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: ${{ github.workflow }}-${{ github.ref }}
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
env:
|
|
||||||
RUST_BACKTRACE: 1
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
###################################################
|
||||||
|
# Formatting
|
||||||
|
###################################################
|
||||||
|
|
||||||
################
|
format:
|
||||||
# Pull Request #
|
name: Check formatting
|
||||||
################
|
|
||||||
|
|
||||||
pr:
|
|
||||||
if: ${{ github.event_name == 'pull_request' }}
|
|
||||||
needs:
|
|
||||||
- bench
|
|
||||||
- codespell
|
|
||||||
- clippy
|
|
||||||
- feature
|
|
||||||
- msrv
|
|
||||||
- release-check
|
|
||||||
- rustfmt
|
|
||||||
- test
|
|
||||||
- test-book
|
|
||||||
- wasm
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- run: true
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install rust
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
|
||||||
##########################
|
|
||||||
# Linting and formatting #
|
|
||||||
##########################
|
|
||||||
|
|
||||||
clippy:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
|
||||||
with:
|
with:
|
||||||
toolchain: stable
|
toolchain: stable
|
||||||
components: clippy
|
|
||||||
|
|
||||||
- run: make cargo.lint
|
|
||||||
|
|
||||||
codespell:
|
|
||||||
name: codespell (Book)
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: codespell-project/actions-codespell@v2
|
|
||||||
with:
|
|
||||||
path: book/
|
|
||||||
|
|
||||||
rustfmt:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: nightly
|
|
||||||
components: rustfmt
|
components: rustfmt
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
- run: make cargo.fmt check=yes
|
- name: Run rustfmt
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
###########
|
|
||||||
# Testing #
|
|
||||||
###########
|
|
||||||
|
|
||||||
bench:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
|
||||||
with:
|
with:
|
||||||
toolchain: stable
|
command: fmt
|
||||||
|
args: -- --check
|
||||||
|
|
||||||
- run: cargo clippy -p juniper_benchmarks --benches -- -D warnings
|
###################################################
|
||||||
- run: cargo bench -p juniper_benchmarks
|
# Main Builds
|
||||||
|
###################################################
|
||||||
|
|
||||||
|
build:
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
|
||||||
feature:
|
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
rust: [stable, beta, nightly]
|
||||||
- { feature: <none>, crate: juniper }
|
os: [ubuntu-latest, windows-latest, macOS-latest]
|
||||||
- { feature: anyhow, crate: juniper }
|
|
||||||
- { feature: "anyhow,backtrace", crate: juniper }
|
|
||||||
- { feature: bigdecimal, crate: juniper }
|
|
||||||
- { feature: bson, crate: juniper }
|
|
||||||
- { feature: chrono, crate: juniper }
|
|
||||||
- { feature: chrono-clock, crate: juniper }
|
|
||||||
- { feature: chrono-tz, crate: juniper }
|
|
||||||
- { feature: expose-test-schema, crate: juniper }
|
|
||||||
- { feature: jiff, crate: juniper }
|
|
||||||
- { feature: rust_decimal, crate: juniper }
|
|
||||||
- { feature: schema-language, crate: juniper }
|
|
||||||
- { feature: time, crate: juniper }
|
|
||||||
- { feature: url, crate: juniper }
|
|
||||||
- { feature: uuid, crate: juniper }
|
|
||||||
- { feature: graphql-transport-ws, crate: juniper_graphql_ws }
|
|
||||||
- { feature: graphql-ws, crate: juniper_graphql_ws }
|
|
||||||
- { feature: <none>, crate: juniper_actix }
|
|
||||||
- { feature: subscriptions, crate: juniper_actix }
|
|
||||||
- { feature: <none>, crate: juniper_axum }
|
|
||||||
- { feature: subscriptions, crate: juniper_axum }
|
|
||||||
- { feature: <none>, crate: juniper_warp }
|
|
||||||
- { feature: subscriptions, crate: juniper_warp }
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- name: Checkout
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
uses: actions/checkout@v2
|
||||||
with:
|
|
||||||
toolchain: nightly
|
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: stable
|
|
||||||
|
|
||||||
- run: cargo +nightly update -Z minimal-versions
|
- name: Install rust
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: ${{ matrix.rust }}
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
- run: cargo check -p ${{ matrix.crate }} --no-default-features
|
- uses: davidB/rust-cargo-make@v1
|
||||||
${{ matrix.feature != '<none>'
|
with:
|
||||||
&& format('--features {0}', matrix.feature)
|
version: '0.20.0'
|
||||||
|| '' }}
|
|
||||||
|
- name: Build and run tests
|
||||||
env:
|
env:
|
||||||
RUSTFLAGS: -D warnings
|
CARGO_MAKE_RUN_CODECOV: true
|
||||||
|
run: |
|
||||||
|
cargo make workspace-ci-flow --no-workspace
|
||||||
|
|
||||||
msrv:
|
###################################################
|
||||||
name: MSRV
|
# WASM Builds
|
||||||
strategy:
|
###################################################
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
msrv: ["1.75.0"]
|
|
||||||
crate:
|
|
||||||
- juniper_codegen
|
|
||||||
- juniper
|
|
||||||
- juniper_subscriptions
|
|
||||||
- juniper_graphql_ws
|
|
||||||
- juniper_actix
|
|
||||||
- juniper_axum
|
|
||||||
#- juniper_hyper
|
|
||||||
- juniper_rocket
|
|
||||||
- juniper_warp
|
|
||||||
os:
|
|
||||||
- ubuntu
|
|
||||||
- macOS
|
|
||||||
- windows
|
|
||||||
include:
|
|
||||||
- { msrv: "1.79.0", crate: "juniper_hyper", os: "ubuntu" }
|
|
||||||
- { msrv: "1.79.0", crate: "juniper_hyper", os: "macOS" }
|
|
||||||
- { msrv: "1.79.0", crate: "juniper_hyper", os: "windows" }
|
|
||||||
runs-on: ${{ matrix.os }}-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: nightly
|
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: ${{ matrix.msrv }}
|
|
||||||
|
|
||||||
- run: cargo +nightly update -Z minimal-versions
|
|
||||||
|
|
||||||
- run: make test.cargo crate=${{ matrix.crate }}
|
|
||||||
|
|
||||||
package:
|
|
||||||
name: check (package)
|
|
||||||
if: ${{ startsWith(github.ref, 'refs/tags/juniper') }}
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: stable
|
|
||||||
|
|
||||||
- name: Parse crate name and version from Git tag
|
|
||||||
id: tag
|
|
||||||
uses: actions-ecosystem/action-regex-match@v2
|
|
||||||
with:
|
|
||||||
text: ${{ github.ref }}
|
|
||||||
regex: '^refs/tags/(([a-z_]+)-v([0-9]+\.[0-9]+\.[0-9]+(-.+)?))$'
|
|
||||||
|
|
||||||
- run: cargo package -p ${{ steps.tag.outputs.group2 }} --all-features
|
|
||||||
|
|
||||||
test:
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
crate:
|
|
||||||
- juniper_codegen
|
|
||||||
- juniper
|
|
||||||
- juniper_subscriptions
|
|
||||||
- juniper_graphql_ws
|
|
||||||
- juniper_integration_tests
|
|
||||||
- juniper_codegen_tests
|
|
||||||
- juniper_actix
|
|
||||||
- juniper_axum
|
|
||||||
- juniper_hyper
|
|
||||||
- juniper_rocket
|
|
||||||
- juniper_warp
|
|
||||||
os:
|
|
||||||
- ubuntu
|
|
||||||
- macOS
|
|
||||||
- windows
|
|
||||||
toolchain:
|
|
||||||
- stable
|
|
||||||
- beta
|
|
||||||
- nightly
|
|
||||||
exclude:
|
|
||||||
- crate: juniper_codegen_tests
|
|
||||||
toolchain: beta
|
|
||||||
- crate: juniper_codegen_tests
|
|
||||||
toolchain: nightly
|
|
||||||
- crate: juniper_codegen_tests
|
|
||||||
os: macOS
|
|
||||||
- crate: juniper_codegen_tests
|
|
||||||
os: windows
|
|
||||||
runs-on: ${{ matrix.os }}-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: ${{ matrix.toolchain }}
|
|
||||||
components: rust-src
|
|
||||||
|
|
||||||
- run: cargo install cargo-careful
|
|
||||||
if: ${{ matrix.toolchain == 'nightly' }}
|
|
||||||
|
|
||||||
- run: make test.cargo crate=${{ matrix.crate }}
|
|
||||||
careful=${{ (matrix.toolchain == 'nightly' && 'yes')
|
|
||||||
|| 'no' }}
|
|
||||||
|
|
||||||
test-book:
|
|
||||||
name: test (Book)
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
os:
|
|
||||||
- ubuntu
|
|
||||||
- macOS
|
|
||||||
- windows
|
|
||||||
toolchain:
|
|
||||||
- stable
|
|
||||||
- beta
|
|
||||||
- nightly
|
|
||||||
runs-on: ${{ matrix.os }}-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: ${{ matrix.toolchain }}
|
|
||||||
- uses: peaceiris/actions-mdbook@v2
|
|
||||||
|
|
||||||
- run: make test.book
|
|
||||||
|
|
||||||
wasm:
|
wasm:
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
matrix:
|
||||||
crate:
|
os: [ubuntu-latest, windows-latest, macOS-latest]
|
||||||
- juniper
|
|
||||||
- juniper_axum
|
|
||||||
target:
|
|
||||||
- wasm32-unknown-unknown
|
|
||||||
- wasm32-wasip1
|
|
||||||
toolchain:
|
|
||||||
- stable
|
|
||||||
- beta
|
|
||||||
- nightly
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- name: Checkout
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
uses: actions/checkout@v2
|
||||||
with:
|
|
||||||
toolchain: ${{ matrix.toolchain }}
|
|
||||||
target: ${{ matrix.target }}
|
|
||||||
|
|
||||||
- name: Switch Cargo workspace to `resolver = "2"`
|
- name: Install rust
|
||||||
run: sed -i 's/resolver = "1"/resolver = "2"/' Cargo.toml
|
uses: actions-rs/toolchain@v1
|
||||||
|
|
||||||
- run: cargo check --target ${{ matrix.target }} -p ${{ matrix.crate }}
|
|
||||||
${{ (matrix.crate == 'juniper' && matrix.target == 'wasm32-unknown-unknown')
|
|
||||||
&& '--features js'
|
|
||||||
|| '' }}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
#############
|
|
||||||
# Releasing #
|
|
||||||
#############
|
|
||||||
|
|
||||||
publish:
|
|
||||||
name: publish (crates.io)
|
|
||||||
if: ${{ startsWith(github.ref, 'refs/tags/juniper') }}
|
|
||||||
needs: ["release-github"]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
|
||||||
with:
|
with:
|
||||||
toolchain: stable
|
toolchain: stable
|
||||||
|
target: wasm32-unknown-unknown
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
- name: Parse crate name and version from Git tag
|
- name: Check
|
||||||
id: tag
|
uses: actions-rs/cargo@v1
|
||||||
uses: actions-ecosystem/action-regex-match@v2
|
|
||||||
with:
|
with:
|
||||||
text: ${{ github.ref }}
|
command: check
|
||||||
regex: '^refs/tags/(([a-z_]+)-v([0-9]+\.[0-9]+\.[0-9]+(-.+)?))$'
|
args: --target wasm32-unknown-unknown --package juniper --package juniper_codegen
|
||||||
|
|
||||||
- run: cargo publish -p ${{ steps.tag.outputs.group2 }} --all-features
|
###################################################
|
||||||
env:
|
# Releases
|
||||||
CARGO_REGISTRY_TOKEN: ${{ secrets.CRATESIO_TOKEN }}
|
###################################################
|
||||||
|
|
||||||
|
release:
|
||||||
|
name: Check release automation
|
||||||
|
|
||||||
release-check:
|
|
||||||
name: check (release)
|
|
||||||
if: ${{ !startsWith(github.ref, 'refs/tags/juniper') }}
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
crate:
|
|
||||||
- juniper_codegen
|
|
||||||
- juniper
|
|
||||||
- juniper_subscriptions
|
|
||||||
- juniper_graphql_ws
|
|
||||||
- juniper_actix
|
|
||||||
- juniper_axum
|
|
||||||
- juniper_hyper
|
|
||||||
- juniper_rocket
|
|
||||||
- juniper_warp
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- name: Checkout
|
||||||
- uses: dtolnay/rust-toolchain@v1
|
uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
fetch-depth: 20
|
||||||
|
|
||||||
|
- name: Install rust
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
with:
|
with:
|
||||||
toolchain: stable
|
toolchain: stable
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
- run: cargo install cargo-release
|
- uses: davidB/rust-cargo-make@v1
|
||||||
|
|
||||||
- run: make cargo.release crate=${{ matrix.crate }} ver=minor
|
|
||||||
exec=no install=no
|
|
||||||
|
|
||||||
release-github:
|
|
||||||
name: release (GitHub)
|
|
||||||
if: ${{ startsWith(github.ref, 'refs/tags/juniper') }}
|
|
||||||
needs:
|
|
||||||
- bench
|
|
||||||
- clippy
|
|
||||||
- codespell
|
|
||||||
- feature
|
|
||||||
- msrv
|
|
||||||
- package
|
|
||||||
- rustfmt
|
|
||||||
- test
|
|
||||||
- test-book
|
|
||||||
- wasm
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Parse crate name and version from Git tag
|
|
||||||
id: tag
|
|
||||||
uses: actions-ecosystem/action-regex-match@v2
|
|
||||||
with:
|
with:
|
||||||
text: ${{ github.ref }}
|
version: '0.20.0'
|
||||||
regex: '^refs/tags/(([a-z_]+)-v([0-9]+\.[0-9]+\.[0-9]+(-.+)?))$'
|
|
||||||
- name: Verify release version matches crate's Cargo manifest
|
- name: Install cargo-release
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: install
|
||||||
|
args: --version=0.11.2 cargo-release
|
||||||
|
|
||||||
|
- name: Setup git
|
||||||
run: |
|
run: |
|
||||||
test "${{ steps.tag.outputs.group3 }}" \
|
git config --global user.email "juniper@example.com"
|
||||||
== "$(grep -m1 'version = "' \
|
git config --global user.name "Release Test Bot"
|
||||||
${{ steps.tag.outputs.group2 }}/Cargo.toml \
|
|
||||||
| cut -d '"' -f2)"
|
|
||||||
|
|
||||||
- name: Parse CHANGELOG link
|
- name: Dry run mode
|
||||||
id: changelog
|
env:
|
||||||
run: echo "link=${{ github.server_url }}/${{ github.repository }}/blob/${{ steps.tag.outputs.group1 }}/${{ steps.tag.outputs.group2 }}/CHANGELOG.md#$(sed -n '/^## \[${{ steps.tag.outputs.group3 }}\]/{s/^## \[\(.*\)\][^0-9]*\([0-9].*\)/\1--\2/;s/[^0-9a-z-]*//g;p;}' ${{ steps.tag.outputs.group2 }}/CHANGELOG.md)"
|
RELEASE_LEVEL: minor
|
||||||
>> $GITHUB_OUTPUT
|
run: |
|
||||||
|
cargo make release-dry-run
|
||||||
|
|
||||||
- name: Create GitHub release
|
- name: Local test mode
|
||||||
uses: softprops/action-gh-release@v2
|
env:
|
||||||
with:
|
RELEASE_LEVEL: minor
|
||||||
name: ${{ steps.tag.outputs.group2 }} ${{ steps.tag.outputs.group3 }}
|
run: |
|
||||||
body: |
|
cargo make release-local-test
|
||||||
[API docs](https://docs.rs/${{ steps.tag.outputs.group2 }}/${{ steps.tag.outputs.group3 }})
|
|
||||||
[Changelog](${{ steps.changelog.outputs.link }})
|
|
||||||
prerelease: ${{ contains(steps.tag.outputs.group3, '-') }}
|
|
||||||
|
|
||||||
|
- name: Echo local changes
|
||||||
|
run: |
|
||||||
|
git --no-pager log -p HEAD...HEAD~20
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
run: |
|
||||||
##########
|
cargo make workspace-ci-flow --no-workspace
|
||||||
# Deploy #
|
|
||||||
##########
|
|
||||||
|
|
||||||
deploy-book:
|
|
||||||
name: deploy (Book)
|
|
||||||
if: ${{ github.ref == 'refs/heads/master'
|
|
||||||
|| startsWith(github.ref, 'refs/tags/juniper') }}
|
|
||||||
needs: ["codespell", "test", "test-book"]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: peaceiris/actions-mdbook@v2
|
|
||||||
|
|
||||||
- run: make book.build out=gh-pages${{ (github.ref == 'refs/heads/master'
|
|
||||||
&& '/master')
|
|
||||||
|| '' }}
|
|
||||||
|
|
||||||
- name: Deploy to GitHub Pages
|
|
||||||
uses: peaceiris/actions-gh-pages@v4
|
|
||||||
with:
|
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
keep_files: true
|
|
||||||
publish_dir: book/gh-pages
|
|
||||||
|
|
10
.gitignore
vendored
10
.gitignore
vendored
|
@ -1,7 +1,3 @@
|
||||||
/.idea/
|
target
|
||||||
/.vscode/
|
Cargo.lock
|
||||||
/*.iml
|
.idea
|
||||||
.DS_Store
|
|
||||||
|
|
||||||
/Cargo.lock
|
|
||||||
/target/
|
|
||||||
|
|
|
@ -17,16 +17,19 @@ Before submitting a PR, you should follow these steps to prevent redundant churn
|
||||||
|
|
||||||
Consistent formatting is enforced on the CI.
|
Consistent formatting is enforced on the CI.
|
||||||
|
|
||||||
Before you submit your PR, you should run `cargo +nightly fmt --all` in the root directory (or use the `make fmt` shortcut).
|
Before you submit your PR, you should run `cargo fmt` in the root directory.
|
||||||
|
|
||||||
Formatting should be run on the **nightly** compiler.
|
Formatting should be run on the **stable** compiler.
|
||||||
|
(You can do `rustup run stable cargo fmt` when developing on nightly)
|
||||||
|
|
||||||
### Run all tests
|
### Run all tests
|
||||||
|
|
||||||
To run all available tests, including verifying the code examples in the book:
|
To run all available tests, including verifying the code examples in the book,
|
||||||
|
you can use [cargo-make](https://github.com/sagiegurari/cargo-make).
|
||||||
|
|
||||||
1. Run `cargo test` in the root directory.
|
1. Install cargo-make with `cargo install cargo-make`
|
||||||
2. Run `make test.book` in the root directory.
|
2. Run `cargo make ci-flow` in the root directory
|
||||||
|
(You can do `rustup run nightly cargo make ci-flow` to run all tests when developing on stable)
|
||||||
|
|
||||||
### Update the CHANGELOG
|
### Update the CHANGELOG
|
||||||
|
|
||||||
|
|
18
Cargo.toml
18
Cargo.toml
|
@ -1,16 +1,24 @@
|
||||||
[workspace]
|
[workspace]
|
||||||
resolver = "1" # unifying Cargo features asap for Book tests
|
# Order is important as this is the order the crates will be released.
|
||||||
members = [
|
members = [
|
||||||
"benches",
|
"juniper_benchmarks",
|
||||||
"juniper_codegen",
|
"juniper_codegen",
|
||||||
"juniper",
|
"juniper",
|
||||||
|
"examples/basic_subscriptions",
|
||||||
|
"examples/warp_async",
|
||||||
|
"examples/warp_subscriptions",
|
||||||
|
"examples/actix_subscriptions",
|
||||||
|
"integration_tests/juniper_tests",
|
||||||
|
"integration_tests/async_await",
|
||||||
|
"integration_tests/codegen_fail",
|
||||||
"juniper_hyper",
|
"juniper_hyper",
|
||||||
|
"juniper_iron",
|
||||||
"juniper_rocket",
|
"juniper_rocket",
|
||||||
"juniper_subscriptions",
|
"juniper_subscriptions",
|
||||||
"juniper_graphql_ws",
|
"juniper_graphql_ws",
|
||||||
"juniper_warp",
|
"juniper_warp",
|
||||||
"juniper_actix",
|
"juniper_actix",
|
||||||
"juniper_axum",
|
]
|
||||||
"tests/codegen",
|
exclude = [
|
||||||
"tests/integration",
|
"docs/book/tests",
|
||||||
]
|
]
|
||||||
|
|
6
LICENSE
6
LICENSE
|
@ -1,10 +1,6 @@
|
||||||
BSD 2-Clause License
|
BSD 2-Clause License
|
||||||
|
|
||||||
Copyright (c) 2016-2025 Magnus Hallin <mhallin@fastmail.com>,
|
Copyright (c) 2016, Magnus Hallin
|
||||||
Christoph Herzog <chris@theduke.at>,
|
|
||||||
Christian Legnitto <christian@legnitto.com>,
|
|
||||||
Ilya Solovyiov <ilya.solovyiov@gmail.com>,
|
|
||||||
Kai Ren <tyranron@gmail.com>
|
|
||||||
All rights reserved.
|
All rights reserved.
|
||||||
|
|
||||||
Redistribution and use in source and binary forms, with or without
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
|
199
Makefile
199
Makefile
|
@ -1,199 +0,0 @@
|
||||||
###############################
|
|
||||||
# Common defaults/definitions #
|
|
||||||
###############################
|
|
||||||
|
|
||||||
comma := ,
|
|
||||||
|
|
||||||
# Checks two given strings for equality.
|
|
||||||
eq = $(if $(or $(1),$(2)),$(and $(findstring $(1),$(2)),\
|
|
||||||
$(findstring $(2),$(1))),1)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
###########
|
|
||||||
# Aliases #
|
|
||||||
###########
|
|
||||||
|
|
||||||
book: book.build
|
|
||||||
|
|
||||||
|
|
||||||
codespell: book.codespell
|
|
||||||
|
|
||||||
|
|
||||||
fmt: cargo.fmt
|
|
||||||
|
|
||||||
|
|
||||||
lint: cargo.lint
|
|
||||||
|
|
||||||
|
|
||||||
test: test.cargo
|
|
||||||
|
|
||||||
|
|
||||||
release: cargo.release
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
##################
|
|
||||||
# Cargo commands #
|
|
||||||
##################
|
|
||||||
|
|
||||||
# Format Rust sources with rustfmt.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# make cargo.fmt [check=(no|yes)]
|
|
||||||
|
|
||||||
cargo.fmt:
|
|
||||||
cargo +nightly fmt --all $(if $(call eq,$(check),yes),-- --check,)
|
|
||||||
|
|
||||||
|
|
||||||
# Lint Rust sources with Clippy.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# make cargo.lint
|
|
||||||
|
|
||||||
cargo.lint:
|
|
||||||
cargo clippy --workspace --all-features -- -D warnings
|
|
||||||
cargo clippy -p juniper_integration_tests --tests --all-features -- -D warnings
|
|
||||||
|
|
||||||
|
|
||||||
# Release Rust crate.
|
|
||||||
#
|
|
||||||
# Read more about bump levels here:
|
|
||||||
# https://github.com/crate-ci/cargo-release/blob/master/docs/reference.md#bump-level
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# make cargo.release crate=<crate-name> [ver=(release|<bump-level>)]
|
|
||||||
# ([exec=no]|exec=yes [push=(yes|no)])
|
|
||||||
# [install=(yes|no)]
|
|
||||||
|
|
||||||
cargo.release:
|
|
||||||
ifneq ($(install),no)
|
|
||||||
cargo install cargo-release
|
|
||||||
endif
|
|
||||||
cargo release -p $(crate) --all-features \
|
|
||||||
$(if $(call eq,$(exec),yes),\
|
|
||||||
--no-publish $(if $(call eq,$(push),no),--no-push,) --execute,\
|
|
||||||
-v $(if $(call eq,$(CI),),,--no-publish)) \
|
|
||||||
$(or $(ver),release)
|
|
||||||
|
|
||||||
|
|
||||||
cargo.test: test.cargo
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
####################
|
|
||||||
# Testing commands #
|
|
||||||
####################
|
|
||||||
|
|
||||||
# Run Rust tests of Book.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# make test.book [clean=(no|yes)]
|
|
||||||
|
|
||||||
test.book:
|
|
||||||
ifeq ($(clean),yes)
|
|
||||||
cargo clean
|
|
||||||
endif
|
|
||||||
$(eval target := $(strip $(shell cargo -vV | sed -n 's/host: //p')))
|
|
||||||
cargo build --all-features
|
|
||||||
mdbook test book -L target/debug/deps $(strip \
|
|
||||||
$(if $(call eq,$(findstring windows,$(target)),),,\
|
|
||||||
$(shell cargo metadata -q \
|
|
||||||
| jq -r '.packages[] | select(.name == "windows_$(word 1,$(subst -, ,$(target)))_$(word 4,$(subst -, ,$(target)))") | .manifest_path' \
|
|
||||||
| sed -e "s/^/-L '/" -e 's/Cargo.toml/lib/' -e "s/$$/'/" )))
|
|
||||||
|
|
||||||
|
|
||||||
# Run Rust tests of project crates.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# make test.cargo [crate=<crate-name>] [careful=(no|yes)]
|
|
||||||
|
|
||||||
test.cargo:
|
|
||||||
ifeq ($(careful),yes)
|
|
||||||
ifeq ($(shell cargo install --list | grep cargo-careful),)
|
|
||||||
cargo install cargo-careful
|
|
||||||
endif
|
|
||||||
ifeq ($(shell rustup component list --toolchain=nightly \
|
|
||||||
| grep 'rust-src (installed)'),)
|
|
||||||
rustup component add --toolchain=nightly rust-src
|
|
||||||
endif
|
|
||||||
endif
|
|
||||||
cargo $(if $(call eq,$(careful),yes),+nightly careful,) \
|
|
||||||
test $(if $(call eq,$(crate),),--workspace,-p $(crate)) --all-features
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
#################
|
|
||||||
# Book commands #
|
|
||||||
#################
|
|
||||||
|
|
||||||
# Build Book.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# make book.build [out=<dir>]
|
|
||||||
|
|
||||||
book.build:
|
|
||||||
mdbook build book/ $(if $(call eq,$(out),),,-d $(out))
|
|
||||||
|
|
||||||
|
|
||||||
# Spellcheck Book.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# make book.codespell [fix=(no|yes)]
|
|
||||||
|
|
||||||
book.codespell:
|
|
||||||
codespell book/ $(if $(call eq,$(fix),yes),--write-changes,)
|
|
||||||
|
|
||||||
|
|
||||||
# Serve Book on some port.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# make book.serve [port=(3000|<port>)]
|
|
||||||
|
|
||||||
book.serve:
|
|
||||||
mdbook serve book/ -p=$(or $(port),3000)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
######################
|
|
||||||
# Forwarded commands #
|
|
||||||
######################
|
|
||||||
|
|
||||||
# Download and prepare actual version of GraphiQL static files, used for
|
|
||||||
# integrating it.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# make graphiql
|
|
||||||
|
|
||||||
graphiql:
|
|
||||||
@cd juniper/ && \
|
|
||||||
make graphiql
|
|
||||||
|
|
||||||
|
|
||||||
# Download and prepare actual version of GraphQL Playground static files, used
|
|
||||||
# for integrating it.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# make graphql-playground
|
|
||||||
|
|
||||||
graphql-playground:
|
|
||||||
@cd juniper/ && \
|
|
||||||
make graphql-playground
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
##################
|
|
||||||
# .PHONY section #
|
|
||||||
##################
|
|
||||||
|
|
||||||
.PHONY: book codespell fmt lint release test \
|
|
||||||
book.build book.codespell book.serve \
|
|
||||||
cargo.fmt cargo.lint cargo.release cargo.test \
|
|
||||||
graphiql graphql-playground \
|
|
||||||
test.book test.cargo
|
|
38
Makefile.toml
Normal file
38
Makefile.toml
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
# https://github.com/sagiegurari/cargo-make#automatically-extend-workspace-makefile
|
||||||
|
[env]
|
||||||
|
CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = "true"
|
||||||
|
CARGO_MAKE_CARGO_ALL_FEATURES = ""
|
||||||
|
CARGO_MAKE_WORKSPACE_SKIP_MEMBERS = "integration_tests/*;examples/*;juniper_benchmarks;"
|
||||||
|
|
||||||
|
|
||||||
|
# Run `RELEASE_LEVEL=(patch|major|minor) cargo make release` to push a new release of every crate.
|
||||||
|
#
|
||||||
|
# Run `RELEASE_LEVEL=(patch|major|minor) CARGO_MAKE_WORKSPACE_INCLUDE_MEMBERS="crate1;crate2;" cargo make release`
|
||||||
|
# to push a new release of a subset of crates.
|
||||||
|
[tasks.release]
|
||||||
|
condition = { env_set = [ "RELEASE_LEVEL" ] }
|
||||||
|
command = "cargo-release"
|
||||||
|
args = ["release", "--config", "${CARGO_MAKE_WORKING_DIRECTORY}/../_build/release.toml", "${RELEASE_LEVEL}"]
|
||||||
|
|
||||||
|
|
||||||
|
# Run `RELEASE_LEVEL=(patch|major|minor) cargo make release-dry-run` to do a dry run.
|
||||||
|
#
|
||||||
|
# Run `RELEASE_LEVEL=(patch|major|minor) CARGO_MAKE_WORKSPACE_INCLUDE_MEMBERS="crate1;crate2;" cargo make release-dry-run`
|
||||||
|
# to do a dry run of a subset of crates.
|
||||||
|
[tasks.release-dry-run]
|
||||||
|
condition = { env_set = [ "RELEASE_LEVEL" ] }
|
||||||
|
description = "Run `cargo-release --dry-run` for every crate"
|
||||||
|
command = "cargo-release"
|
||||||
|
args = ["release", "--config", "${CARGO_MAKE_WORKING_DIRECTORY}/../_build/release.toml", "--dry-run", "${RELEASE_LEVEL}"]
|
||||||
|
|
||||||
|
|
||||||
|
# Run `RELEASE_LEVEL=(patch|major|minor) cargo make release-local-test` to actually make changes locally but
|
||||||
|
# not push them up to crates.io or Github.
|
||||||
|
#
|
||||||
|
# Run `RELEASE_LEVEL=(patch|major|minor) CARGO_MAKE_WORKSPACE_INCLUDE_MEMBERS="crate1;crate2;" cargo make release-local-test` to actually make changes locally but
|
||||||
|
# not push some crates up to crates.io or Github.
|
||||||
|
[tasks.release-local-test]
|
||||||
|
condition = { env_set = [ "RELEASE_LEVEL" ] }
|
||||||
|
description = "Run `cargo-release` for every crate, but only make changes locally"
|
||||||
|
command = "cargo-release"
|
||||||
|
args = ["release", "--config", "${CARGO_MAKE_WORKING_DIRECTORY}/../_build/release.toml", "--no-confirm", "--skip-publish", "--skip-push", "--skip-tag", "${RELEASE_LEVEL}"]
|
24
README.md
24
README.md
|
@ -5,7 +5,7 @@
|
||||||
[![Build Status](https://dev.azure.com/graphql-rust/GraphQL%20Rust/_apis/build/status/graphql-rust.juniper)](https://dev.azure.com/graphql-rust/GraphQL%20Rust/_build/latest?definitionId=1)
|
[![Build Status](https://dev.azure.com/graphql-rust/GraphQL%20Rust/_apis/build/status/graphql-rust.juniper)](https://dev.azure.com/graphql-rust/GraphQL%20Rust/_build/latest?definitionId=1)
|
||||||
[![codecov](https://codecov.io/gh/graphql-rust/juniper/branch/master/graph/badge.svg)](https://codecov.io/gh/graphql-rust/juniper)
|
[![codecov](https://codecov.io/gh/graphql-rust/juniper/branch/master/graph/badge.svg)](https://codecov.io/gh/graphql-rust/juniper)
|
||||||
[![Crates.io](https://img.shields.io/crates/v/juniper.svg?maxAge=2592000)](https://crates.io/crates/juniper)
|
[![Crates.io](https://img.shields.io/crates/v/juniper.svg?maxAge=2592000)](https://crates.io/crates/juniper)
|
||||||
[![Gitter chat](https://badges.gitter.im/juniper-graphql/gitter.svg)](https://gitter.im/juniper-graphql/Lobby)
|
[![Gitter chat](https://badges.gitter.im/juniper-graphql/gitter.svg)](https://gitter.im/juniper-graphql)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -18,7 +18,7 @@ GraphQL schemas as convenient as Rust will allow.
|
||||||
|
|
||||||
Juniper does not include a web server - instead it provides building blocks to
|
Juniper does not include a web server - instead it provides building blocks to
|
||||||
make integration with existing servers straightforward. It optionally provides a
|
make integration with existing servers straightforward. It optionally provides a
|
||||||
pre-built integration for the [Actix][actix], [Hyper][hyper], [Rocket], and [Warp][warp] frameworks, including
|
pre-built integration for the [Actix][actix], [Hyper][hyper], [Iron][iron], [Rocket], and [Warp][warp] frameworks, including
|
||||||
embedded [Graphiql][graphiql] and [GraphQL Playground][playground] for easy debugging.
|
embedded [Graphiql][graphiql] and [GraphQL Playground][playground] for easy debugging.
|
||||||
|
|
||||||
- [Cargo crate](https://crates.io/crates/juniper)
|
- [Cargo crate](https://crates.io/crates/juniper)
|
||||||
|
@ -42,12 +42,12 @@ For specific information about macros, types and the Juniper api, the
|
||||||
You can also check out the [Star Wars schema][test_schema_rs] to see a complex
|
You can also check out the [Star Wars schema][test_schema_rs] to see a complex
|
||||||
example including polymorphism with traits and interfaces.
|
example including polymorphism with traits and interfaces.
|
||||||
For an example of web framework integration,
|
For an example of web framework integration,
|
||||||
see the [actix][actix_examples], [axum][axum_examples], [hyper][hyper_examples], [rocket][rocket_examples], and [warp][warp_examples] examples folders.
|
see the [actix][actix_examples], [hyper][hyper_examples], [rocket][rocket_examples], [iron][iron_examples], and [warp][warp_examples] examples folders.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
Juniper supports the full GraphQL query language according to the
|
Juniper supports the full GraphQL query language according to the
|
||||||
[specification (October 2021)][graphql_spec], including interfaces, unions, schema
|
[specification][graphql_spec], including interfaces, unions, schema
|
||||||
introspection, and validations. It can also output the schema in the [GraphQL Schema Language][schema_language].
|
introspection, and validations. It can also output the schema in the [GraphQL Schema Language][schema_language].
|
||||||
|
|
||||||
As an exception to other GraphQL libraries for other languages, Juniper builds
|
As an exception to other GraphQL libraries for other languages, Juniper builds
|
||||||
|
@ -73,16 +73,15 @@ your Schemas automatically.
|
||||||
- [url][url]
|
- [url][url]
|
||||||
- [chrono][chrono]
|
- [chrono][chrono]
|
||||||
- [chrono-tz][chrono-tz]
|
- [chrono-tz][chrono-tz]
|
||||||
- [jiff][jiff]
|
|
||||||
- [time][time]
|
- [time][time]
|
||||||
- [bson][bson]
|
- [bson][bson]
|
||||||
|
|
||||||
### Web Frameworks
|
### Web Frameworks
|
||||||
|
|
||||||
- [actix][actix]
|
- [actix][actix]
|
||||||
- [axum][axum]
|
|
||||||
- [hyper][hyper]
|
- [hyper][hyper]
|
||||||
- [rocket][rocket]
|
- [rocket][rocket]
|
||||||
|
- [iron][iron]
|
||||||
- [warp][warp]
|
- [warp][warp]
|
||||||
|
|
||||||
## Guides & Examples
|
## Guides & Examples
|
||||||
|
@ -94,25 +93,25 @@ your Schemas automatically.
|
||||||
Juniper has not reached 1.0 yet, thus some API instability should be expected.
|
Juniper has not reached 1.0 yet, thus some API instability should be expected.
|
||||||
|
|
||||||
[actix]: https://actix.rs/
|
[actix]: https://actix.rs/
|
||||||
[axum]: https://docs.rs/axum
|
|
||||||
[graphql]: http://graphql.org
|
[graphql]: http://graphql.org
|
||||||
[graphiql]: https://github.com/graphql/graphiql
|
[graphiql]: https://github.com/graphql/graphiql
|
||||||
[playground]: https://github.com/prisma/graphql-playground
|
[playground]: https://github.com/prisma/graphql-playground
|
||||||
[graphql_spec]: https://spec.graphql.org/October2021
|
[iron]: https://github.com/iron/iron
|
||||||
|
[graphql_spec]: http://facebook.github.io/graphql
|
||||||
[schema_language]: https://graphql.org/learn/schema/#type-language
|
[schema_language]: https://graphql.org/learn/schema/#type-language
|
||||||
[schema_approach]: https://blog.logrocket.com/code-first-vs-schema-first-development-graphql/
|
[schema_approach]: https://blog.logrocket.com/code-first-vs-schema-first-development-graphql/
|
||||||
[test_schema_rs]: https://github.com/graphql-rust/juniper/blob/master/juniper/src/tests/fixtures/starwars/schema.rs
|
[test_schema_rs]: https://github.com/graphql-rust/juniper/blob/master/juniper/src/tests/fixtures/starwars/schema.rs
|
||||||
[tokio]: https://github.com/tokio-rs/tokio
|
[tokio]: https://github.com/tokio-rs/tokio
|
||||||
[actix_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_actix/examples
|
[actix_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_actix/examples
|
||||||
[axum_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_axum/examples
|
|
||||||
[hyper_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_hyper/examples
|
[hyper_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_hyper/examples
|
||||||
[rocket_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_rocket/examples
|
[rocket_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_rocket/examples
|
||||||
|
[iron_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_iron/examples
|
||||||
[hyper]: https://hyper.rs
|
[hyper]: https://hyper.rs
|
||||||
[rocket]: https://rocket.rs
|
[rocket]: https://rocket.rs
|
||||||
[book]: https://graphql-rust.github.io/juniper
|
[book]: https://graphql-rust.github.io
|
||||||
[book_master]: https://graphql-rust.github.io/juniper/master
|
[book_master]: https://graphql-rust.github.io/juniper/master
|
||||||
[book_index]: https://graphql-rust.github.io/juniper
|
[book_index]: https://graphql-rust.github.io
|
||||||
[book_quickstart]: https://graphql-rust.github.io/juniper/quickstart.html
|
[book_quickstart]: https://graphql-rust.github.io/quickstart.html
|
||||||
[docsrs]: https://docs.rs/juniper
|
[docsrs]: https://docs.rs/juniper
|
||||||
[warp]: https://github.com/seanmonstar/warp
|
[warp]: https://github.com/seanmonstar/warp
|
||||||
[warp_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_warp/examples
|
[warp_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_warp/examples
|
||||||
|
@ -120,7 +119,6 @@ Juniper has not reached 1.0 yet, thus some API instability should be expected.
|
||||||
[url]: https://crates.io/crates/url
|
[url]: https://crates.io/crates/url
|
||||||
[chrono]: https://crates.io/crates/chrono
|
[chrono]: https://crates.io/crates/chrono
|
||||||
[chrono-tz]: https://crates.io/crates/chrono-tz
|
[chrono-tz]: https://crates.io/crates/chrono-tz
|
||||||
[jiff]: https://crates.io/crates/jiff
|
|
||||||
[time]: https://crates.io/crates/time
|
[time]: https://crates.io/crates/time
|
||||||
[bson]: https://crates.io/crates/bson
|
[bson]: https://crates.io/crates/bson
|
||||||
[juniper-from-schema]: https://github.com/davidpdrsn/juniper-from-schema
|
[juniper-from-schema]: https://github.com/davidpdrsn/juniper-from-schema
|
||||||
|
|
87
RELEASING.md
87
RELEASING.md
|
@ -1,59 +1,74 @@
|
||||||
Releasing new crate versions
|
# How to release new crate versions
|
||||||
============================
|
|
||||||
|
|
||||||
Releasing of [workspace] crates of this project is performed by pushing the Git release tag (having `<crate-name>@<version>` format), following by the [CI pipeline] creating a [GitHub release] and publishing the crate to [crates.io].
|
|
||||||
|
|
||||||
> __WARNING__: Only one [workspace] crate may be released at a time. So, if you need to release multiple [workspace] crates, do this sequentially.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Prerequisites
|
## Prerequisites
|
||||||
|
|
||||||
We use [`cargo-release`] to automate crate releases. You will need to install it locally:
|
It is generally best to start with a clean respository dedicated to a release so that no git weirdness happens:
|
||||||
```bash
|
|
||||||
cargo install cargo-release
|
```
|
||||||
|
git clone git@github.com:graphql-rust/juniper.git juniper_release;
|
||||||
|
cd juniper_release;
|
||||||
```
|
```
|
||||||
|
|
||||||
|
We use the `nightly` toolchain when releasing. This is because some of our crates require nightly:
|
||||||
|
|
||||||
|
`rustup default nightly`
|
||||||
|
|
||||||
|
We use [`cargo-make`](cargo-make) and [`cargo-release`](cargo-release) to automate crate releases. You will need to install them locally:
|
||||||
|
|
||||||
## Preparing
|
- `cargo install -f cargo-make`
|
||||||
|
- `cargo install -f cargo-release`
|
||||||
|
|
||||||
To produce a new release a [workspace] crate, perform the following steps:
|
## Preparing for a release
|
||||||
|
|
||||||
1. Check its `CHANGELOG.md` file to be complete and correctly formatted. The section for the new release __should start__ with `## master` header. Commit any changes you've made.
|
There are two general classes of releases:
|
||||||
|
|
||||||
2. Determine a new release [bump level] (`patch`, `minor`, `major`, or default `release`).
|
1. All public workspace crates should be released and all share the same release level ("patch", "minor", "major").
|
||||||
|
|
||||||
3. Run the release process in dry-run mode and check the produced diffs to be made in the returned output.
|
2. A subset of workspace crates need to be released, or not all crate releases share the same release level.
|
||||||
```bash
|
|
||||||
make release crate=juniper ver=minor
|
|
||||||
```
|
|
||||||
|
|
||||||
4. (Optional) Not everything may be captured in dry-run mode. It may be a good idea to run a local test, without pushing the created Git commit and tag.
|
**All release commands must be run from the root directory of the repository.**
|
||||||
```bash
|
|
||||||
make release crate=juniper ver=minor exec=yes push=no
|
|
||||||
```
|
|
||||||
|
|
||||||
|
## Determine new release level
|
||||||
|
|
||||||
|
For each crate, determine the desired release level (`patch`, `minor`, `major`). Set the `RELEASE_LEVEL` env variable to the desired release level.
|
||||||
|
|
||||||
|
## Determine which crates to release
|
||||||
|
|
||||||
## Executing
|
If a subset of workspace crates need to be released, or not all crate releases share the same release level, set the `CARGO_MAKE_WORKSPACE_INCLUDE_MEMBERS` env
|
||||||
|
variable to choose specific workspace crates. The value is a list of semicolon-delineated crate names or a regular expressions.
|
||||||
|
|
||||||
Once everything is prepared and checked, just execute the releasing process:
|
## Dry run
|
||||||
```bash
|
|
||||||
make release crate=juniper ver=minor exec=yes
|
|
||||||
```
|
|
||||||
|
|
||||||
Once the [CI pipeline] for the pushed Git tag successfully finishes, the crate is fully released.
|
It is a good idea to do a dry run to sanity check what actions will be performed.
|
||||||
|
|
||||||
|
- For case #1 above, run `cargo make release-dry-run`.
|
||||||
|
- For case #2 above, run `CARGO_MAKE_WORKSPACE_INCLUDE_MEMBERS="crate1;crate2" cargo make release-dry-run`.
|
||||||
|
|
||||||
|
If the command finishes super quickly with no output you likely did not set `RELEASE_LEVEL`.
|
||||||
|
|
||||||
|
## Local test
|
||||||
|
|
||||||
[`cargo-release`]: https://crates.io/crates/cargo-release
|
Not everything is captured in the dry run. It is a good idea to run a local test.
|
||||||
[CI pipeline]: /../../blob/master/.github/workflows/ci.yml
|
In a local test, all the release actions are performed on your local checkout
|
||||||
[crates.io]: https://crates.io
|
but nothing is pushed to Github or crates.io.
|
||||||
[GitHub release]: https://docs.github.com/repositories/releasing-projects-on-github/about-releases
|
|
||||||
[release level]: https://github.com/crate-ci/cargo-release/blob/master/docs/reference.md#bump-level
|
- For case #1 above, run `cargo make release-local-test`.
|
||||||
[workspace]: https://doc.rust-lang.org/cargo/reference/workspaces.html
|
- For case #2 above, run `CARGO_MAKE_WORKSPACE_INCLUDE_MEMBERS="crate1;crate2" cargo make release-local-test`.
|
||||||
|
|
||||||
|
If the command finishes super quickly with no output you likely did not set `RELEASE_LEVEL`.
|
||||||
|
|
||||||
|
After, your local git repository should have the changes ready to push to Github.
|
||||||
|
Use `git rebase -i HEAD~10` and drop the new commits.
|
||||||
|
|
||||||
|
## Release
|
||||||
|
|
||||||
|
After testing locally and via a dry run, it is time to release. A release
|
||||||
|
consists of bumping versions, starting a new changelog section, pushing a tag to Github, and updating crates.io. This should all be handled by running the automated commands.
|
||||||
|
|
||||||
|
- For case #1 above, run `cargo make release`.
|
||||||
|
- For case #2 above, run `CARGO_MAKE_WORKSPACE_INCLUDE_MEMBERS="crate1;crate2" cargo make release`.
|
||||||
|
|
||||||
|
If the command finishes super quickly with no output you likely did not set `RELEASE_LEVEL`,
|
||||||
|
|
||||||
|
[cargo-make]: https://github.com/sagiegurari/cargo-make
|
||||||
|
[cargo-release]: https://github.com/sunng87/cargo-release
|
||||||
|
|
71
_build/azure-pipelines-template.yml
Normal file
71
_build/azure-pipelines-template.yml
Normal file
|
@ -0,0 +1,71 @@
|
||||||
|
jobs:
|
||||||
|
- job: ${{ parameters.name }}
|
||||||
|
pool:
|
||||||
|
vmImage: ${{ parameters.vmImage }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
stable:
|
||||||
|
rustup_toolchain: stable
|
||||||
|
beta:
|
||||||
|
rustup_toolchain: beta
|
||||||
|
nightly:
|
||||||
|
rustup_toolchain: nightly
|
||||||
|
# TODO: re-enable once new versions are released.
|
||||||
|
# minimum_supported_version_plus_one:
|
||||||
|
# rustup_toolchain: 1.32.0
|
||||||
|
#minimum_supported_version:
|
||||||
|
# rustup_toolchain: 1.33.0
|
||||||
|
steps:
|
||||||
|
- ${{ if ne(parameters.name, 'Windows') }}:
|
||||||
|
# Linux and macOS.
|
||||||
|
- script: |
|
||||||
|
export CARGO_HOME="$HOME/.cargo"
|
||||||
|
curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain $RUSTUP_TOOLCHAIN
|
||||||
|
echo "##vso[task.setvariable variable=PATH;]$PATH:$HOME/.cargo/bin"
|
||||||
|
displayName: Install rust
|
||||||
|
- ${{ if eq(parameters.name, 'Windows') }}:
|
||||||
|
# Windows.
|
||||||
|
- script: |
|
||||||
|
set CARGO_HOME=%USERPROFILE%\.cargo
|
||||||
|
curl -sSf -o rustup-init.exe https://win.rustup.rs
|
||||||
|
rustup-init.exe -y --default-toolchain %RUSTUP_TOOLCHAIN%
|
||||||
|
set PATH=%PATH%;%USERPROFILE%\.cargo\bin
|
||||||
|
echo "##vso[task.setvariable variable=PATH;]%PATH%;%USERPROFILE%\.cargo\bin"
|
||||||
|
displayName: Install rust (windows)
|
||||||
|
# All platforms.
|
||||||
|
- script: |
|
||||||
|
rustc -Vv
|
||||||
|
cargo -V
|
||||||
|
displayName: Query rust and cargo versions
|
||||||
|
- ${{ if eq(parameters.name, 'Linux') }}:
|
||||||
|
# Linux.
|
||||||
|
- script: _build/cargo-make.sh "0.20.0" "x86_64-unknown-linux-musl"
|
||||||
|
displayName: Install cargo-make binary
|
||||||
|
- ${{ if eq(parameters.name, 'macOS') }}:
|
||||||
|
# Mac.
|
||||||
|
- script: _build/cargo-make.sh "0.20.0" "x86_64-apple-darwin"
|
||||||
|
displayName: Install cargo-make binary
|
||||||
|
- ${{ if eq(parameters.name, 'Windows') }}:
|
||||||
|
# Windows.
|
||||||
|
- script: powershell -executionpolicy bypass -file _build/cargo-make.ps1 -version "0.20.0" -target "x86_64-pc-windows-msvc"
|
||||||
|
displayName: Install cargo-make binary
|
||||||
|
- ${{ if eq(parameters.name, 'Windows') }}:
|
||||||
|
# Windows.
|
||||||
|
- script: |
|
||||||
|
set PATH=%PATH%;%USERPROFILE%\.cargo\bin
|
||||||
|
cargo make workspace-ci-flow --no-workspace
|
||||||
|
env: { CARGO_MAKE_RUN_CODECOV: true }
|
||||||
|
displayName: Build and run tests
|
||||||
|
- ${{ if ne(parameters.name, 'Windows') }}:
|
||||||
|
# Not Windows.
|
||||||
|
- script: |
|
||||||
|
export PATH="$PATH:$HOME/.cargo/bin";
|
||||||
|
cargo make workspace-ci-flow --no-workspace
|
||||||
|
env: { CARGO_MAKE_RUN_CODECOV: true }
|
||||||
|
displayName: Build and run tests
|
||||||
|
|
||||||
|
- script: |
|
||||||
|
rustup target add wasm32-unknown-unknown
|
||||||
|
cargo check --target wasm32-unknown-unknown --package juniper --package juniper_codegen
|
||||||
|
displayName: Check WebAssembly target
|
||||||
|
condition: eq(variables['rustup_toolchain'], 'stable')
|
21
_build/cargo-make.ps1
Normal file
21
_build/cargo-make.ps1
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
param (
|
||||||
|
[Parameter(Mandatory=$true)][string]$version,
|
||||||
|
[Parameter(Mandatory=$true)][string]$target
|
||||||
|
)
|
||||||
|
|
||||||
|
# Location to put cargo-make binary.
|
||||||
|
$cargobindir = "$env:userprofile\.cargo\bin"
|
||||||
|
|
||||||
|
# Location to stage downloaded zip file.
|
||||||
|
$zipfile = "$env:temp\cargo-make.zip"
|
||||||
|
|
||||||
|
$url = "https://github.com/sagiegurari/cargo-make/releases/download/${version}/cargo-make-v${version}-${target}.zip"
|
||||||
|
|
||||||
|
# Download the zip file.
|
||||||
|
Invoke-WebRequest -Uri $url -OutFile $zipfile
|
||||||
|
|
||||||
|
# Extract the binary to the correct location.
|
||||||
|
Expand-Archive -Path $zipfile -DestinationPath $cargobindir
|
||||||
|
|
||||||
|
# Tell azure pipelines the PATH has changed for future steps.
|
||||||
|
Write-Host "##vso[task.setvariable variable=PATH;]%PATH%;$cargobindir"
|
19
_build/cargo-make.sh
Executable file
19
_build/cargo-make.sh
Executable file
|
@ -0,0 +1,19 @@
|
||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
if [ -z ${1+x} ];
|
||||||
|
then
|
||||||
|
echo "Missing version as first argument";
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -z ${2+x} ];
|
||||||
|
then
|
||||||
|
echo "Missing target as second argument";
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
curl https://github.com/sagiegurari/cargo-make/releases/download/${1}/cargo-make-v${1}-${2}.zip -sSfL -o /tmp/cargo-make.zip;
|
||||||
|
unzip /tmp/cargo-make.zip;
|
||||||
|
mkdir -p "$HOME/.cargo/bin";
|
||||||
|
mv cargo-make-*/* $HOME/.cargo/bin;
|
||||||
|
echo "##vso[task.setvariable variable=PATH;]$PATH:$HOME/.cargo/bin"
|
7
_build/release.toml
Normal file
7
_build/release.toml
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
no-dev-version = true
|
||||||
|
pre-release-commit-message = "Release {{crate_name}} {{version}}"
|
||||||
|
pro-release-commit-message = "Bump {{crate_name}} version to {{next_version}}"
|
||||||
|
tag-message = "Release {{crate_name}} {{version}}"
|
||||||
|
pre-release-replacements = [
|
||||||
|
{file="CHANGELOG.md", min=0, search="# master", replace="# master\n\n- Compatibility with the latest `juniper`.\n\n# [[{{version}}] {{date}}](https://github.com/graphql-rust/juniper/releases/tag/{{crate_name}}-{{version}})"},
|
||||||
|
]
|
1
_build/travis-juniper.enc
Normal file
1
_build/travis-juniper.enc
Normal file
|
@ -0,0 +1 @@
|
||||||
|
´LÅØAtÙèù˜Û‡uÙË}k¦b÷Œ«<C592>iíãxN»ÔJÛb'OÅ’€6°¤ê·Äs–Þ`(¯vZeòaˆ°Î`ëPÝ‚W[DæW4¾®€Ïe¡·» <C2BB>«ï9¥¿4
ÀÖžgF÷‘ûa¸P‚ýŒ5ò õ/8FQܪ"Bß ~þBrº’¢Ž8@)†Ê0 yeÍĆ»·–²ŠàCù·»º´F¹"m§±òö¡wûÑ?<3F>INŽTŠ(tõlß•SÀ%K_3ð¾2ò–§^Š^kMLMTJÛÕ½¾Z7cÁüzÖ&qÆsd²H‚¢^¨•‡
|
109
azure-pipelines.yml
Normal file
109
azure-pipelines.yml
Normal file
|
@ -0,0 +1,109 @@
|
||||||
|
jobs:
|
||||||
|
###################################################
|
||||||
|
# Formatting
|
||||||
|
###################################################
|
||||||
|
|
||||||
|
- job: check_formatting
|
||||||
|
displayName: Check formatting
|
||||||
|
pool:
|
||||||
|
vmImage: 'ubuntu-latest'
|
||||||
|
steps:
|
||||||
|
- script: |
|
||||||
|
export CARGO_HOME="$HOME/.cargo"
|
||||||
|
curl https://sh.rustup.rs -sSf | sh -s -- -y
|
||||||
|
$HOME/.cargo/bin/rustup component add rustfmt
|
||||||
|
displayName: Install stable Rust
|
||||||
|
- script: |
|
||||||
|
$HOME/.cargo/bin/cargo fmt -- --check
|
||||||
|
displayName: Run rustfmt
|
||||||
|
|
||||||
|
###################################################
|
||||||
|
# Book
|
||||||
|
###################################################
|
||||||
|
|
||||||
|
- job: run_book_tests
|
||||||
|
displayName: Book code example tests
|
||||||
|
pool:
|
||||||
|
vmImage: 'ubuntu-latest'
|
||||||
|
steps:
|
||||||
|
- script: |
|
||||||
|
export CARGO_HOME="$HOME/.cargo"
|
||||||
|
curl https://sh.rustup.rs -sSf | sh -s -- -y
|
||||||
|
$HOME/.cargo/bin/rustup component add rustfmt
|
||||||
|
displayName: Install stable Rust
|
||||||
|
- script: |
|
||||||
|
cd docs/book/tests && $HOME/.cargo/bin/cargo test
|
||||||
|
displayName: Test book code examples via skeptic
|
||||||
|
|
||||||
|
- job: build_book_master
|
||||||
|
displayName: Build rendered book on master branch and push to Github
|
||||||
|
pool:
|
||||||
|
vmImage: 'ubuntu-latest'
|
||||||
|
dependsOn: run_book_tests
|
||||||
|
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/master'))
|
||||||
|
variables:
|
||||||
|
- group: github-keys
|
||||||
|
steps:
|
||||||
|
- task: InstallSSHKey@0
|
||||||
|
inputs:
|
||||||
|
hostName: $(GHSshKnownHosts)
|
||||||
|
sshPublicKey: $(GHSshPub)
|
||||||
|
sshKeySecureFile: $(GHSshPriv)
|
||||||
|
- script: |
|
||||||
|
./docs/book/ci-build.sh master
|
||||||
|
|
||||||
|
###################################################
|
||||||
|
# Main Builds
|
||||||
|
###################################################
|
||||||
|
|
||||||
|
- template: _build/azure-pipelines-template.yml
|
||||||
|
parameters:
|
||||||
|
name: Linux
|
||||||
|
vmImage: 'ubuntu-latest'
|
||||||
|
|
||||||
|
- template: _build/azure-pipelines-template.yml
|
||||||
|
parameters:
|
||||||
|
name: macOS
|
||||||
|
vmImage: 'macOS-latest'
|
||||||
|
|
||||||
|
- template: _build/azure-pipelines-template.yml
|
||||||
|
parameters:
|
||||||
|
name: Windows
|
||||||
|
vmImage: 'windows-latest'
|
||||||
|
|
||||||
|
###################################################
|
||||||
|
# Releases
|
||||||
|
###################################################
|
||||||
|
|
||||||
|
- job: check_release_automation
|
||||||
|
displayName: Check release automation
|
||||||
|
pool:
|
||||||
|
vmImage: 'ubuntu-latest'
|
||||||
|
steps:
|
||||||
|
- script: |
|
||||||
|
export CARGO_HOME="$HOME/.cargo"
|
||||||
|
curl https://sh.rustup.rs -sSf | sh -s -- -y
|
||||||
|
echo "##vso[task.setvariable variable=PATH;]$PATH:$HOME/.cargo/bin"
|
||||||
|
displayName: Install stable Rust
|
||||||
|
- script: |
|
||||||
|
_build/cargo-make.sh "0.20.0" "x86_64-unknown-linux-musl"
|
||||||
|
displayName: Install cargo-make binary
|
||||||
|
- script: |
|
||||||
|
cargo install --debug --version=0.11.2 cargo-release
|
||||||
|
displayName: Install cargo-release binary
|
||||||
|
- script: |
|
||||||
|
git config --local user.name "Release Test Bot"
|
||||||
|
git config --local user.email "juniper@example.com"
|
||||||
|
displayName: Set up git
|
||||||
|
- script: |
|
||||||
|
RELEASE_LEVEL="minor" cargo make release-dry-run
|
||||||
|
displayName: Dry run mode
|
||||||
|
- script: |
|
||||||
|
RELEASE_LEVEL="minor" cargo make release-local-test
|
||||||
|
displayName: Local test mode
|
||||||
|
- script: |
|
||||||
|
git --no-pager log -p HEAD...HEAD~20
|
||||||
|
# NOTE: this is rolled into one task due to onerous
|
||||||
|
# "bash not found" error on Azure.
|
||||||
|
cargo make workspace-ci-flow --no-workspace
|
||||||
|
displayName: Echo local changes && make sure build and tests still work
|
|
@ -1,80 +0,0 @@
|
||||||
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
|
|
||||||
|
|
||||||
use juniper::InputValue;
|
|
||||||
use juniper_benchmarks as j;
|
|
||||||
|
|
||||||
fn bench_sync_vs_async_users_flat_instant(c: &mut Criterion) {
|
|
||||||
// language=GraphQL
|
|
||||||
const ASYNC_QUERY: &str = r#"
|
|
||||||
query Query($id: Int) {
|
|
||||||
users_async_instant(ids: [$id]!) {
|
|
||||||
id
|
|
||||||
kind
|
|
||||||
username
|
|
||||||
email
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"#;
|
|
||||||
|
|
||||||
// language=GraphQL
|
|
||||||
const SYNC_QUERY: &str = r#"
|
|
||||||
query Query($id: Int) {
|
|
||||||
users_sync_instant(ids: [$id]!) {
|
|
||||||
id
|
|
||||||
kind
|
|
||||||
username
|
|
||||||
email
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"#;
|
|
||||||
|
|
||||||
let mut group = c.benchmark_group("Sync vs Async - Users Flat - Instant");
|
|
||||||
for count in [1, 10] {
|
|
||||||
group.bench_function(BenchmarkId::new("Sync", count), |b| {
|
|
||||||
let ids = (0..count).map(InputValue::scalar).collect::<Vec<_>>();
|
|
||||||
let ids = InputValue::list(ids);
|
|
||||||
b.iter(|| {
|
|
||||||
j::execute_sync(
|
|
||||||
SYNC_QUERY,
|
|
||||||
vec![("ids".to_owned(), ids.clone())].into_iter().collect(),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
group.bench_function(BenchmarkId::new("Async - Single Thread", count), |b| {
|
|
||||||
let rt = tokio::runtime::Builder::new_current_thread()
|
|
||||||
.build()
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let ids = (0..count).map(InputValue::scalar).collect::<Vec<_>>();
|
|
||||||
let ids = InputValue::list(ids);
|
|
||||||
|
|
||||||
b.iter(|| {
|
|
||||||
let f = j::execute(
|
|
||||||
ASYNC_QUERY,
|
|
||||||
vec![("ids".to_owned(), ids.clone())].into_iter().collect(),
|
|
||||||
);
|
|
||||||
rt.block_on(f)
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
group.bench_function(BenchmarkId::new("Async - Threadpool", count), |b| {
|
|
||||||
let rt = tokio::runtime::Builder::new_multi_thread().build().unwrap();
|
|
||||||
|
|
||||||
let ids = (0..count).map(InputValue::scalar).collect::<Vec<_>>();
|
|
||||||
let ids = InputValue::list(ids);
|
|
||||||
|
|
||||||
b.iter(|| {
|
|
||||||
let f = j::execute(
|
|
||||||
ASYNC_QUERY,
|
|
||||||
vec![("ids".to_owned(), ids.clone())].into_iter().collect(),
|
|
||||||
);
|
|
||||||
rt.block_on(f)
|
|
||||||
})
|
|
||||||
});
|
|
||||||
}
|
|
||||||
group.finish();
|
|
||||||
}
|
|
||||||
|
|
||||||
criterion_group!(benches, bench_sync_vs_async_users_flat_instant);
|
|
||||||
criterion_main!(benches);
|
|
2
book/.gitignore
vendored
2
book/.gitignore
vendored
|
@ -1,2 +0,0 @@
|
||||||
/_rendered/
|
|
||||||
/gh-pages/
|
|
|
@ -1,55 +0,0 @@
|
||||||
Juniper Book
|
|
||||||
============
|
|
||||||
|
|
||||||
Book containing the [`juniper`](https://docs.rs/juniper) user guide.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Contributing
|
|
||||||
|
|
||||||
|
|
||||||
### Requirements
|
|
||||||
|
|
||||||
The Book is built with [mdBook](https://github.com/rust-lang/mdBook).
|
|
||||||
|
|
||||||
You may install it with:
|
|
||||||
```bash
|
|
||||||
cargo install mdbook
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Local test server
|
|
||||||
|
|
||||||
To launch a local test server that continually re-builds the Book and auto-reloads the page, run:
|
|
||||||
```bash
|
|
||||||
mdbook serve
|
|
||||||
|
|
||||||
# or from project root dir:
|
|
||||||
make book.serve
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Building
|
|
||||||
|
|
||||||
You may build the Book to rendered HTML with this command:
|
|
||||||
```bash
|
|
||||||
mdbook build
|
|
||||||
|
|
||||||
# or from project root dir:
|
|
||||||
make book
|
|
||||||
```
|
|
||||||
|
|
||||||
The output will be in the `_rendered/` directory.
|
|
||||||
|
|
||||||
|
|
||||||
### Testing
|
|
||||||
|
|
||||||
To run the tests validating all code examples in the book, run (from project root dir):
|
|
||||||
```bash
|
|
||||||
cargo build
|
|
||||||
mdbook test -L target/debug/deps
|
|
||||||
|
|
||||||
# or via shortcut:
|
|
||||||
make test.book
|
|
||||||
```
|
|
|
@ -1,19 +0,0 @@
|
||||||
[book]
|
|
||||||
title = "Juniper Book"
|
|
||||||
description = "User guide for Juniper (GraphQL server library for Rust)."
|
|
||||||
language = "en"
|
|
||||||
multilingual = false
|
|
||||||
authors = [
|
|
||||||
"Kai Ren (@tyranron)",
|
|
||||||
]
|
|
||||||
src = "src"
|
|
||||||
|
|
||||||
[build]
|
|
||||||
build-dir = "_rendered"
|
|
||||||
create-missing = false
|
|
||||||
|
|
||||||
[output.html]
|
|
||||||
git_repository_url = "https://github.com/graphql-rust/juniper"
|
|
||||||
|
|
||||||
[rust]
|
|
||||||
edition = "2021"
|
|
|
@ -1,28 +0,0 @@
|
||||||
# Summary
|
|
||||||
|
|
||||||
- [Introduction](introduction.md)
|
|
||||||
- [Quickstart](quickstart.md)
|
|
||||||
- [Type system](types/index.md)
|
|
||||||
- [Objects](types/objects/index.md)
|
|
||||||
- [Complex fields](types/objects/complex_fields.md)
|
|
||||||
- [Context](types/objects/context.md)
|
|
||||||
- [Error handling](types/objects/error/index.md)
|
|
||||||
- [Field errors](types/objects/error/field.md)
|
|
||||||
- [Schema errors](types/objects/error/schema.md)
|
|
||||||
- [Generics](types/objects/generics.md)
|
|
||||||
- [Interfaces](types/interfaces.md)
|
|
||||||
- [Unions](types/unions.md)
|
|
||||||
- [Enums](types/enums.md)
|
|
||||||
- [Input objects](types/input_objects.md)
|
|
||||||
- [Scalars](types/scalars.md)
|
|
||||||
- [Schema](schema/index.md)
|
|
||||||
- [Subscriptions](schema/subscriptions.md)
|
|
||||||
- [Introspection](schema/introspection.md)
|
|
||||||
- [Serving](serve/index.md)
|
|
||||||
- [Batching](serve/batching.md)
|
|
||||||
- [Advanced Topics](advanced/index.md)
|
|
||||||
- [Implicit and explicit `null`](advanced/implicit_and_explicit_null.md)
|
|
||||||
- [N+1 problem](advanced/n_plus_1.md)
|
|
||||||
- [DataLoader](advanced/dataloader.md)
|
|
||||||
- [Look-ahead](advanced/lookahead.md)
|
|
||||||
- [Eager loading](advanced/eager_loading.md)
|
|
|
@ -1,198 +0,0 @@
|
||||||
DataLoader
|
|
||||||
==========
|
|
||||||
|
|
||||||
DataLoader pattern, named after the correspondent [`dataloader` NPM package][0], represents a mechanism of batching and caching data requests in a delayed manner for solving the [N+1 problem](n_plus_1.md).
|
|
||||||
|
|
||||||
> A port of the "Loader" API originally developed by [@schrockn] at Facebook in 2010 as a simplifying force to coalesce the sundry key-value store back-end APIs which existed at the time. At Facebook, "Loader" became one of the implementation details of the "Ent" framework, a privacy-aware data entity loading and caching layer within web server product code. This ultimately became the underpinning for Facebook's GraphQL server implementation and type definitions.
|
|
||||||
|
|
||||||
In [Rust] ecosystem, DataLoader pattern is introduced with the [`dataloader` crate][1], naturally usable with [Juniper].
|
|
||||||
|
|
||||||
Let's remake our [example of N+1 problem](n_plus_1.md), so it's solved by applying the DataLoader pattern:
|
|
||||||
```rust
|
|
||||||
# extern crate anyhow;
|
|
||||||
# extern crate dataloader;
|
|
||||||
# extern crate juniper;
|
|
||||||
# use std::{collections::HashMap, sync::Arc};
|
|
||||||
# use anyhow::anyhow;
|
|
||||||
# use dataloader::non_cached::Loader;
|
|
||||||
# use juniper::{graphql_object, GraphQLObject};
|
|
||||||
#
|
|
||||||
# type CultId = i32;
|
|
||||||
# type UserId = i32;
|
|
||||||
#
|
|
||||||
# struct Repository;
|
|
||||||
#
|
|
||||||
# impl Repository {
|
|
||||||
# async fn load_cults_by_ids(&self, cult_ids: &[CultId]) -> anyhow::Result<HashMap<CultId, Cult>> { unimplemented!() }
|
|
||||||
# async fn load_all_persons(&self) -> anyhow::Result<Vec<Person>> { unimplemented!() }
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
struct Context {
|
|
||||||
repo: Repository,
|
|
||||||
cult_loader: CultLoader,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl juniper::Context for Context {}
|
|
||||||
|
|
||||||
#[derive(Clone, GraphQLObject)]
|
|
||||||
struct Cult {
|
|
||||||
id: CultId,
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct CultBatcher {
|
|
||||||
repo: Repository,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Since `BatchFn` doesn't provide any notion of fallible loading, like
|
|
||||||
// `try_load()` returning `Result<HashMap<K, V>, E>`, we handle possible
|
|
||||||
// errors as loaded values and unpack them later in the resolver.
|
|
||||||
impl dataloader::BatchFn<CultId, Result<Cult, Arc<anyhow::Error>>> for CultBatcher {
|
|
||||||
async fn load(
|
|
||||||
&mut self,
|
|
||||||
cult_ids: &[CultId],
|
|
||||||
) -> HashMap<CultId, Result<Cult, Arc<anyhow::Error>>> {
|
|
||||||
// Effectively performs the following SQL query:
|
|
||||||
// SELECT id, name FROM cults WHERE id IN (${cult_id1}, ${cult_id2}, ...)
|
|
||||||
match self.repo.load_cults_by_ids(cult_ids).await {
|
|
||||||
Ok(found_cults) => {
|
|
||||||
found_cults.into_iter().map(|(id, cult)| (id, Ok(cult))).collect()
|
|
||||||
}
|
|
||||||
// One could choose a different strategy to deal with fallible loads,
|
|
||||||
// like consider values that failed to load as absent, or just panic.
|
|
||||||
// See cksac/dataloader-rs#35 for details:
|
|
||||||
// https://github.com/cksac/dataloader-rs/issues/35
|
|
||||||
Err(e) => {
|
|
||||||
// Since `anyhow::Error` doesn't implement `Clone`, we have to
|
|
||||||
// work around here.
|
|
||||||
let e = Arc::new(e);
|
|
||||||
cult_ids.iter().map(|k| (k.clone(), Err(e.clone()))).collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type CultLoader = Loader<CultId, Result<Cult, Arc<anyhow::Error>>, CultBatcher>;
|
|
||||||
|
|
||||||
fn new_cult_loader(repo: Repository) -> CultLoader {
|
|
||||||
CultLoader::new(CultBatcher { repo })
|
|
||||||
// Usually a `Loader` will coalesce all individual loads which occur
|
|
||||||
// within a single frame of execution before calling a `BatchFn::load()`
|
|
||||||
// with all the collected keys. However, sometimes this behavior is not
|
|
||||||
// desirable or optimal (perhaps, a request is expected to be spread out
|
|
||||||
// over a few subsequent ticks).
|
|
||||||
// A larger yield count will allow more keys to be appended to the batch,
|
|
||||||
// but will wait longer before the actual load. For more details see:
|
|
||||||
// https://github.com/cksac/dataloader-rs/issues/12
|
|
||||||
// https://github.com/graphql/dataloader#batch-scheduling
|
|
||||||
.with_yield_count(100)
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Person {
|
|
||||||
id: UserId,
|
|
||||||
name: String,
|
|
||||||
cult_id: CultId,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(context = Context)]
|
|
||||||
impl Person {
|
|
||||||
fn id(&self) -> CultId {
|
|
||||||
self.id
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
self.name.as_str()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn cult(&self, ctx: &Context) -> anyhow::Result<Cult> {
|
|
||||||
ctx.cult_loader
|
|
||||||
// Here, we don't run the `CultBatcher::load()` eagerly, but rather
|
|
||||||
// only register the `self.cult_id` value in the `cult_loader` and
|
|
||||||
// wait for other concurrent resolvers to do the same.
|
|
||||||
// The actual batch loading happens once all the resolvers register
|
|
||||||
// their IDs and there is nothing more to execute.
|
|
||||||
.try_load(self.cult_id)
|
|
||||||
.await
|
|
||||||
// The outer error is the `io::Error` returned by `try_load()` if
|
|
||||||
// no value is present in the `HashMap` for the specified
|
|
||||||
// `self.cult_id`, meaning that there is no `Cult` with such ID
|
|
||||||
// in the `Repository`.
|
|
||||||
.map_err(|_| anyhow!("No cult exists for ID `{}`", self.cult_id))?
|
|
||||||
// The inner error is the one returned by the `CultBatcher::load()`
|
|
||||||
// if the `Repository::load_cults_by_ids()` fails, meaning that
|
|
||||||
// running the SQL query failed.
|
|
||||||
.map_err(|arc_err| anyhow!("{arc_err}"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Query;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(context = Context)]
|
|
||||||
impl Query {
|
|
||||||
async fn persons(ctx: &Context) -> anyhow::Result<Vec<Person>> {
|
|
||||||
// Effectively performs the following SQL query:
|
|
||||||
// SELECT id, name, cult_id FROM persons
|
|
||||||
ctx.repo.load_all_persons().await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
And now, performing a [GraphQL query which lead to N+1 problem](n_plus_1.md)
|
|
||||||
```graphql
|
|
||||||
query {
|
|
||||||
persons {
|
|
||||||
id
|
|
||||||
name
|
|
||||||
cult {
|
|
||||||
id
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
will lead to efficient [SQL] queries, just as expected:
|
|
||||||
```sql
|
|
||||||
SELECT id, name, cult_id FROM persons;
|
|
||||||
SELECT id, name FROM cults WHERE id IN (1, 2, 3, 4);
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Caching
|
|
||||||
|
|
||||||
[`dataloader::cached`] provides a [memoization][2] cache: after `BatchFn::load()` is called once with given keys, the resulting values are cached to eliminate redundant loads.
|
|
||||||
|
|
||||||
DataLoader caching does not replace [Redis], [Memcached], or any other shared application-level cache. DataLoader is first and foremost a data loading mechanism, and its cache only serves the purpose of not repeatedly loading the same data [in the context of a single request][3].
|
|
||||||
|
|
||||||
> **WARNING**: A DataLoader should be created per-request to avoid risk of bugs where one client is able to load cached/batched data from another client outside its authenticated scope. Creating a DataLoader within an individual resolver will prevent batching from occurring and will nullify any benefits of it.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Full example
|
|
||||||
|
|
||||||
For a full example using DataLoaders in [Juniper] check out the [`jayy-lmao/rust-graphql-docker` repository][4].
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[`dataloader::cached`]: https://docs.rs/dataloader/latest/dataloader/cached/index.html
|
|
||||||
[@schrockn]: https://github.com/schrockn
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Memcached]: https://memcached.org
|
|
||||||
[Redis]: https://redis.io
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
[SQL]: https://en.wikipedia.org/wiki/SQL
|
|
||||||
|
|
||||||
[0]: https://github.com/graphql/dataloader
|
|
||||||
[1]: https://docs.rs/crate/dataloader
|
|
||||||
[2]: https://en.wikipedia.org/wiki/Memoization
|
|
||||||
[3]: https://github.com/graphql/dataloader#caching
|
|
||||||
[4]: https://github.com/jayy-lmao/rust-graphql-docker
|
|
|
@ -1,280 +0,0 @@
|
||||||
Eager loading
|
|
||||||
=============
|
|
||||||
|
|
||||||
As a further evolution of the [dealing with the N+1 problem via look-ahead](lookahead.md#n1-problem), we may systematically remodel [Rust] types mapping to [GraphQL] ones in the way to encourage doing eager preloading of data for its [fields][0] and using the already preloaded data when resolving a particular [field][0].
|
|
||||||
|
|
||||||
At the moment, this approach is represented with the [`juniper-eager-loading`] crate for [Juniper].
|
|
||||||
|
|
||||||
> **NOTE**: Since this library requires [`juniper-from-schema`], it's best first to become familiar with it.
|
|
||||||
|
|
||||||
<!-- TODO: Provide example of solving the problem from "N+1 chapter" once `juniper-eager-loading` support the latest `juniper`. -->
|
|
||||||
|
|
||||||
From ["How this library works at a high level"][11] and ["A real example"][12] sections of [`juniper-eager-loading`] documentation:
|
|
||||||
|
|
||||||
> ### How this library works at a high level
|
|
||||||
>
|
|
||||||
> If you have a GraphQL type like this
|
|
||||||
>
|
|
||||||
> ```graphql
|
|
||||||
> type User {
|
|
||||||
> id: Int!
|
|
||||||
> country: Country!
|
|
||||||
> }
|
|
||||||
> ```
|
|
||||||
>
|
|
||||||
> You might create the corresponding Rust model type like this:
|
|
||||||
>
|
|
||||||
> ```rust
|
|
||||||
> struct User {
|
|
||||||
> id: i32,
|
|
||||||
> country_id: i32,
|
|
||||||
> }
|
|
||||||
> ```
|
|
||||||
>
|
|
||||||
> However this approach has one big issue. How are you going to resolve the field `User.country`
|
|
||||||
> without doing a database query? All the resolver has access to is a `User` with a `country_id`
|
|
||||||
> field. It can't get the country without loading it from the database...
|
|
||||||
>
|
|
||||||
> Fundamentally these kinds of model structs don't work for eager loading with GraphQL. So
|
|
||||||
> this library takes a different approach.
|
|
||||||
>
|
|
||||||
> What if we created separate structs for the database models and the GraphQL models? Something
|
|
||||||
> like this:
|
|
||||||
>
|
|
||||||
> ```rust
|
|
||||||
> # fn main() {}
|
|
||||||
> #
|
|
||||||
> mod models {
|
|
||||||
> pub struct User {
|
|
||||||
> id: i32,
|
|
||||||
> country_id: i32
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> pub struct Country {
|
|
||||||
> id: i32,
|
|
||||||
> }
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> struct User {
|
|
||||||
> user: models::User,
|
|
||||||
> country: HasOne<Country>,
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> struct Country {
|
|
||||||
> country: models::Country
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> enum HasOne<T> {
|
|
||||||
> Loaded(T),
|
|
||||||
> NotLoaded,
|
|
||||||
> }
|
|
||||||
> ```
|
|
||||||
>
|
|
||||||
> Now we're able to resolve the query with code like this:
|
|
||||||
>
|
|
||||||
> 1. Load all the users (first query).
|
|
||||||
> 2. Map the users to a list of country ids.
|
|
||||||
> 3. Load all the countries with those ids (second query).
|
|
||||||
> 4. Pair up the users with the country with the correct id, so change `User.country` from
|
|
||||||
> `HasOne::NotLoaded` to `HasOne::Loaded(matching_country)`.
|
|
||||||
> 5. When resolving the GraphQL field `User.country` simply return the loaded country.
|
|
||||||
>
|
|
||||||
> ### A real example
|
|
||||||
>
|
|
||||||
> ```rust,ignore
|
|
||||||
> use juniper::{Executor, FieldResult};
|
|
||||||
> use juniper_eager_loading::{prelude::*, EagerLoading, HasOne};
|
|
||||||
> use juniper_from_schema::graphql_schema;
|
|
||||||
> use std::error::Error;
|
|
||||||
>
|
|
||||||
> // Define our GraphQL schema.
|
|
||||||
> graphql_schema! {
|
|
||||||
> schema {
|
|
||||||
> query: Query
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> type Query {
|
|
||||||
> allUsers: [User!]! @juniper(ownership: "owned")
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> type User {
|
|
||||||
> id: Int!
|
|
||||||
> country: Country!
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> type Country {
|
|
||||||
> id: Int!
|
|
||||||
> }
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> // Our model types.
|
|
||||||
> mod models {
|
|
||||||
> use std::error::Error;
|
|
||||||
> use juniper_eager_loading::LoadFrom;
|
|
||||||
>
|
|
||||||
> #[derive(Clone)]
|
|
||||||
> pub struct User {
|
|
||||||
> pub id: i32,
|
|
||||||
> pub country_id: i32
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> #[derive(Clone)]
|
|
||||||
> pub struct Country {
|
|
||||||
> pub id: i32,
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> // This trait is required for eager loading countries.
|
|
||||||
> // It defines how to load a list of countries from a list of ids.
|
|
||||||
> // Notice that `Context` is generic and can be whatever you want.
|
|
||||||
> // It will normally be your Juniper context which would contain
|
|
||||||
> // a database connection.
|
|
||||||
> impl LoadFrom<i32> for Country {
|
|
||||||
> type Error = Box<dyn Error>;
|
|
||||||
> type Context = super::Context;
|
|
||||||
>
|
|
||||||
> fn load(
|
|
||||||
> employments: &[i32],
|
|
||||||
> field_args: &(),
|
|
||||||
> ctx: &Self::Context,
|
|
||||||
> ) -> Result<Vec<Self>, Self::Error> {
|
|
||||||
> // ...
|
|
||||||
> # unimplemented!()
|
|
||||||
> }
|
|
||||||
> }
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> // Our sample database connection type.
|
|
||||||
> pub struct DbConnection;
|
|
||||||
>
|
|
||||||
> impl DbConnection {
|
|
||||||
> // Function that will load all the users.
|
|
||||||
> fn load_all_users(&self) -> Vec<models::User> {
|
|
||||||
> // ...
|
|
||||||
> # unimplemented!()
|
|
||||||
> }
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> // Our Juniper context type which contains a database connection.
|
|
||||||
> pub struct Context {
|
|
||||||
> db: DbConnection,
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> impl juniper::Context for Context {}
|
|
||||||
>
|
|
||||||
> // Our GraphQL user type.
|
|
||||||
> // `#[derive(EagerLoading)]` takes care of generating all the boilerplate code.
|
|
||||||
> #[derive(Clone, EagerLoading)]
|
|
||||||
> // You need to set the context and error type.
|
|
||||||
> #[eager_loading(
|
|
||||||
> context = Context,
|
|
||||||
> error = Box<dyn Error>,
|
|
||||||
>
|
|
||||||
> // These match the default so you wouldn't have to specify them
|
|
||||||
> model = models::User,
|
|
||||||
> id = i32,
|
|
||||||
> root_model_field = user,
|
|
||||||
> )]
|
|
||||||
> pub struct User {
|
|
||||||
> // This user model is used to resolve `User.id`
|
|
||||||
> user: models::User,
|
|
||||||
>
|
|
||||||
> // Setup a "has one" association between a user and a country.
|
|
||||||
> //
|
|
||||||
> // We could also have used `#[has_one(default)]` here.
|
|
||||||
> #[has_one(
|
|
||||||
> foreign_key_field = country_id,
|
|
||||||
> root_model_field = country,
|
|
||||||
> graphql_field = country,
|
|
||||||
> )]
|
|
||||||
> country: HasOne<Country>,
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> // And the GraphQL country type.
|
|
||||||
> #[derive(Clone, EagerLoading)]
|
|
||||||
> #[eager_loading(context = Context, error = Box<dyn Error>)]
|
|
||||||
> pub struct Country {
|
|
||||||
> country: models::Country,
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> // The root query GraphQL type.
|
|
||||||
> pub struct Query;
|
|
||||||
>
|
|
||||||
> impl QueryFields for Query {
|
|
||||||
> // The resolver for `Query.allUsers`.
|
|
||||||
> fn field_all_users(
|
|
||||||
> &self,
|
|
||||||
> executor: &Executor<'_, Context>,
|
|
||||||
> trail: &QueryTrail<'_, User, Walked>,
|
|
||||||
> ) -> FieldResult<Vec<User>> {
|
|
||||||
> let ctx = executor.context();
|
|
||||||
>
|
|
||||||
> // Load the model users.
|
|
||||||
> let user_models = ctx.db.load_all_users();
|
|
||||||
>
|
|
||||||
> // Turn the model users into GraphQL users.
|
|
||||||
> let mut users = User::from_db_models(&user_models);
|
|
||||||
>
|
|
||||||
> // Perform the eager loading.
|
|
||||||
> // `trail` is used to only eager load the fields that are requested. Because
|
|
||||||
> // we're using `QueryTrail`s from "juniper_from_schema" it would be a compile
|
|
||||||
> // error if we eager loaded associations that aren't requested in the query.
|
|
||||||
> User::eager_load_all_children_for_each(&mut users, &user_models, ctx, trail)?;
|
|
||||||
>
|
|
||||||
> Ok(users)
|
|
||||||
> }
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> impl UserFields for User {
|
|
||||||
> fn field_id(
|
|
||||||
> &self,
|
|
||||||
> executor: &Executor<'_, Context>,
|
|
||||||
> ) -> FieldResult<&i32> {
|
|
||||||
> Ok(&self.user.id)
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> fn field_country(
|
|
||||||
> &self,
|
|
||||||
> executor: &Executor<'_, Context>,
|
|
||||||
> trail: &QueryTrail<'_, Country, Walked>,
|
|
||||||
> ) -> FieldResult<&Country> {
|
|
||||||
> // This will unwrap the country from the `HasOne` or return an error if the
|
|
||||||
> // country wasn't loaded, or wasn't found in the database.
|
|
||||||
> Ok(self.country.try_unwrap()?)
|
|
||||||
> }
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> impl CountryFields for Country {
|
|
||||||
> fn field_id(
|
|
||||||
> &self,
|
|
||||||
> executor: &Executor<'_, Context>,
|
|
||||||
> ) -> FieldResult<&i32> {
|
|
||||||
> Ok(&self.country.id)
|
|
||||||
> }
|
|
||||||
> }
|
|
||||||
> #
|
|
||||||
> # fn main() {}
|
|
||||||
> ```
|
|
||||||
|
|
||||||
For more details, check out the [`juniper-eager-loading` documentation][`juniper-eager-loading`].
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Full example
|
|
||||||
|
|
||||||
For a full example using eager loading in [Juniper] check out the [`davidpdrsn/graphql-app-example` repository][10].
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[`juniper-eager-loading`]: https://docs.rs/juniper-eager-loading
|
|
||||||
[`juniper-from-schema`]: https://docs.rs/juniper-from-schema
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Redis]: https://redis.io
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Language.Fields
|
|
||||||
[10]: https://github.com/davidpdrsn/graphql-app-example
|
|
||||||
[11]: https://docs.rs/juniper-eager-loading/latest/juniper_eager_loading#how-this-library-works-at-a-high-level
|
|
||||||
[12]: https://docs.rs/juniper-eager-loading/latest/juniper_eager_loading#a-real-example
|
|
|
@ -1,117 +0,0 @@
|
||||||
Implicit and explicit `null`
|
|
||||||
============================
|
|
||||||
|
|
||||||
> [GraphQL] has two semantically different ways to represent the lack of a value:
|
|
||||||
> - Explicitly providing the literal value: **null**.
|
|
||||||
> - Implicitly not providing a value at all.
|
|
||||||
|
|
||||||
There are two ways that a client can submit a [`null` value][0] as an [argument][5] or a [field][4] in a [GraphQL] query:
|
|
||||||
1. Either use an explicit `null` literal:
|
|
||||||
```graphql
|
|
||||||
{
|
|
||||||
field(arg: null)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
2. Or simply omit the [argument][5], so the implicit default `null` value kicks in:
|
|
||||||
```graphql
|
|
||||||
{
|
|
||||||
field
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
There are some situations where it's useful to know which one exactly has been provided.
|
|
||||||
|
|
||||||
For example, let's say we have a function that allows users to perform a "patch" operation on themselves. Let's say our users can optionally have favorite and least favorite numbers, and the input for that might look like this:
|
|
||||||
```rust
|
|
||||||
/// Updates user attributes. Fields that are [`None`] are left as-is.
|
|
||||||
struct UserPatch {
|
|
||||||
/// If [`Some`], updates the user's favorite number.
|
|
||||||
favorite_number: Option<Option<i32>>,
|
|
||||||
|
|
||||||
/// If [`Some`], updates the user's least favorite number.
|
|
||||||
least_favorite_number: Option<Option<i32>>,
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
To set a user's favorite number to 7, we would set `favorite_number` to `Some(Some(7))`. In [GraphQL], that might look like this:
|
|
||||||
```graphql
|
|
||||||
mutation { patchUser(patch: { favoriteNumber: 7 }) }
|
|
||||||
```
|
|
||||||
|
|
||||||
To unset the user's favorite number, we would set `favorite_number` to `Some(None)`. In [GraphQL], that might look like this:
|
|
||||||
```graphql
|
|
||||||
mutation { patchUser(patch: { favoriteNumber: null }) }
|
|
||||||
```
|
|
||||||
|
|
||||||
And if we want to leave the user's favorite number alone, just set it to `None`. In [GraphQL], that might look like this:
|
|
||||||
```graphql
|
|
||||||
mutation { patchUser(patch: {}) }
|
|
||||||
```
|
|
||||||
|
|
||||||
The last two cases rely on being able to distinguish between [explicit and implicit `null`][1].
|
|
||||||
|
|
||||||
Unfortunately, plain `Option` is not capable to distinguish them. That's why in [Juniper], this can be done using the [`Nullable`] type:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
use juniper::{graphql_object, FieldResult, GraphQLInputObject, Nullable};
|
|
||||||
|
|
||||||
#[derive(GraphQLInputObject)]
|
|
||||||
struct UserPatchInput {
|
|
||||||
favorite_number: Nullable<i32>,
|
|
||||||
least_favorite_number: Nullable<i32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<UserPatchInput> for UserPatch {
|
|
||||||
fn from(input: UserPatchInput) -> Self {
|
|
||||||
Self {
|
|
||||||
// The `explicit()` function transforms the `Nullable` into an
|
|
||||||
// `Option<Option<T>>` as expected by the business logic layer.
|
|
||||||
favorite_number: input.favorite_number.explicit(),
|
|
||||||
least_favorite_number: input.least_favorite_number.explicit(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# struct UserPatch {
|
|
||||||
# favorite_number: Option<Option<i32>>,
|
|
||||||
# least_favorite_number: Option<Option<i32>>,
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
# struct Session;
|
|
||||||
# impl Session {
|
|
||||||
# fn patch_user(&self, _patch: UserPatch) -> FieldResult<()> { Ok(()) }
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
struct Context {
|
|
||||||
session: Session,
|
|
||||||
}
|
|
||||||
impl juniper::Context for Context {}
|
|
||||||
|
|
||||||
struct Mutation;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(context = Context)]
|
|
||||||
impl Mutation {
|
|
||||||
fn patch_user(patch: UserPatchInput, ctx: &Context) -> FieldResult<bool> {
|
|
||||||
ctx.session.patch_user(patch.into())?;
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[`Nullable`]: https://docs.rs/juniper/0.16.1/juniper/enum.Nullable.html
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Null-Value
|
|
||||||
[1]: https://spec.graphql.org/October2021#sel-EAFdRDHAAEJDAoBxzT
|
|
||||||
[4]: https://spec.graphql.org/October2021#sec-Language.Fields
|
|
||||||
[5]: https://spec.graphql.org/October2021#sec-Language.Arguments
|
|
|
@ -1,10 +0,0 @@
|
||||||
Advanced topics
|
|
||||||
===============
|
|
||||||
|
|
||||||
The chapters below cover some more advanced topics.
|
|
||||||
|
|
||||||
- [Implicit and explicit `null`](implicit_and_explicit_null.md)
|
|
||||||
- [N+1 problem](n_plus_1.md)
|
|
||||||
- [DataLoader](dataloader.md)
|
|
||||||
- [Look-ahead](lookahead.md)
|
|
||||||
- [Eager loading](eager_loading.md)
|
|
|
@ -1,229 +0,0 @@
|
||||||
Look-ahead
|
|
||||||
==========
|
|
||||||
|
|
||||||
> In backtracking algorithms, **look ahead** is the generic term for a subprocedure that attempts to foresee the effects of choosing a branching variable to evaluate one of its values. The two main aims of look-ahead are to choose a variable to evaluate next and to choose the order of values to assign to it.
|
|
||||||
|
|
||||||
In [GraphQL], look-ahead machinery allows us to introspect the currently [executed][1] [GraphQL operation][2] to see which [fields][3] has been actually selected by it.
|
|
||||||
|
|
||||||
In [Juniper], it's represented by the [`Executor::look_ahead()`][20] method.
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_object, Executor, GraphQLObject, ScalarValue};
|
|
||||||
#
|
|
||||||
# type UserId = i32;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Person {
|
|
||||||
id: UserId,
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Query;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
// NOTICE: Specifying `ScalarValue` as custom named type parameter,
|
|
||||||
// so its name is similar to the one used in methods.
|
|
||||||
#[graphql(scalar = S: ScalarValue)]
|
|
||||||
impl Query {
|
|
||||||
fn persons<S: ScalarValue>(executor: &Executor<'_, '_, (), S>) -> Vec<Person> {
|
|
||||||
// Let's see which `Person`'s fields were selected in the client query.
|
|
||||||
for field_name in executor.look_ahead().children().names() {
|
|
||||||
dbg!(field_name);
|
|
||||||
}
|
|
||||||
// ...
|
|
||||||
# unimplemented!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
> **TIP**: `S: ScalarValue` type parameter on the method is required here to keep the [`Executor`] being generic over [`ScalarValue`] types. We, instead, could have used the [`DefaultScalarValue`], which is the default [`ScalarValue`] type for the [`Executor`], and make our code more ergonomic, but less flexible and generic.
|
|
||||||
> ```rust
|
|
||||||
> # extern crate juniper;
|
|
||||||
> # use juniper::{graphql_object, DefaultScalarValue, Executor, GraphQLObject};
|
|
||||||
> #
|
|
||||||
> # type UserId = i32;
|
|
||||||
> #
|
|
||||||
> # #[derive(GraphQLObject)]
|
|
||||||
> # struct Person {
|
|
||||||
> # id: UserId,
|
|
||||||
> # name: String,
|
|
||||||
> # }
|
|
||||||
> #
|
|
||||||
> # struct Query;
|
|
||||||
> #
|
|
||||||
> #[graphql_object]
|
|
||||||
> #[graphql(scalar = DefaultScalarValue)]
|
|
||||||
> impl Query {
|
|
||||||
> fn persons(executor: &Executor<'_, '_, ()>) -> Vec<Person> {
|
|
||||||
> for field_name in executor.look_ahead().children().names() {
|
|
||||||
> dbg!(field_name);
|
|
||||||
> }
|
|
||||||
> // ...
|
|
||||||
> # unimplemented!()
|
|
||||||
> }
|
|
||||||
> }
|
|
||||||
> ```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## N+1 problem
|
|
||||||
|
|
||||||
Naturally, look-ahead machinery allows us to solve [the N+1 problem](n_plus_1.md) by introspecting the requested fields and performing loading in batches eagerly, before actual resolving of those fields:
|
|
||||||
```rust
|
|
||||||
# extern crate anyhow;
|
|
||||||
# extern crate juniper;
|
|
||||||
# use std::collections::HashMap;
|
|
||||||
# use anyhow::anyhow;
|
|
||||||
# use juniper::{graphql_object, Executor, GraphQLObject, ScalarValue};
|
|
||||||
#
|
|
||||||
# type CultId = i32;
|
|
||||||
# type UserId = i32;
|
|
||||||
#
|
|
||||||
# struct Repository;
|
|
||||||
#
|
|
||||||
# impl juniper::Context for Repository {}
|
|
||||||
#
|
|
||||||
# impl Repository {
|
|
||||||
# async fn load_cult_by_id(&self, cult_id: CultId) -> anyhow::Result<Option<Cult>> { unimplemented!() }
|
|
||||||
# async fn load_cults_by_ids(&self, cult_ids: &[CultId]) -> anyhow::Result<HashMap<CultId, Cult>> { unimplemented!() }
|
|
||||||
# async fn load_all_persons(&self) -> anyhow::Result<Vec<Person>> { unimplemented!() }
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
# enum Either<L, R> {
|
|
||||||
# Absent(L),
|
|
||||||
# Loaded(R),
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
#[derive(Clone, GraphQLObject)]
|
|
||||||
struct Cult {
|
|
||||||
id: CultId,
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Person {
|
|
||||||
id: UserId,
|
|
||||||
name: String,
|
|
||||||
cult: Either<CultId, Cult>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(context = Repository)]
|
|
||||||
impl Person {
|
|
||||||
fn id(&self) -> CultId {
|
|
||||||
self.id
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
self.name.as_str()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn cult(&self, #[graphql(ctx)] repo: &Repository) -> anyhow::Result<Cult> {
|
|
||||||
match &self.cult {
|
|
||||||
Either::Loaded(cult) => Ok(cult.clone()),
|
|
||||||
Either::Absent(cult_id) => {
|
|
||||||
// Effectively performs the following SQL query:
|
|
||||||
// SELECT id, name FROM cults WHERE id = ${cult_id} LIMIT 1
|
|
||||||
repo.load_cult_by_id(*cult_id)
|
|
||||||
.await?
|
|
||||||
.ok_or_else(|| anyhow!("No cult exists for ID `{cult_id}`"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Query;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(context = Repository, scalar = S: ScalarValue)]
|
|
||||||
impl Query {
|
|
||||||
async fn persons<S: ScalarValue>(
|
|
||||||
#[graphql(ctx)] repo: &Repository,
|
|
||||||
executor: &Executor<'_, '_, Repository, S>,
|
|
||||||
) -> anyhow::Result<Vec<Person>> {
|
|
||||||
// Effectively performs the following SQL query:
|
|
||||||
// SELECT id, name, cult_id FROM persons
|
|
||||||
let mut persons = repo.load_all_persons().await?;
|
|
||||||
|
|
||||||
// If the `Person.cult` field has been requested.
|
|
||||||
if executor.look_ahead()
|
|
||||||
.children()
|
|
||||||
.iter()
|
|
||||||
.any(|sel| sel.field_original_name() == "cult")
|
|
||||||
{
|
|
||||||
// Gather `Cult.id`s to load eagerly.
|
|
||||||
let cult_ids = persons
|
|
||||||
.iter()
|
|
||||||
.filter_map(|p| {
|
|
||||||
match &p.cult {
|
|
||||||
Either::Absent(cult_id) => Some(*cult_id),
|
|
||||||
// If for some reason a `Cult` is already loaded,
|
|
||||||
// then just skip it.
|
|
||||||
Either::Loaded(_) => None,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
// Load the necessary `Cult`s eagerly.
|
|
||||||
// Effectively performs the following SQL query:
|
|
||||||
// SELECT id, name FROM cults WHERE id IN (${cult_id1}, ${cult_id2}, ...)
|
|
||||||
let cults = repo.load_cults_by_ids(&cult_ids).await?;
|
|
||||||
|
|
||||||
// Populate `persons` with the loaded `Cult`s, so they do not perform
|
|
||||||
// any SQL queries on resolving.
|
|
||||||
for p in &mut persons {
|
|
||||||
let Either::Absent(cult_id) = &p.cult else { continue; };
|
|
||||||
p.cult = Either::Loaded(
|
|
||||||
cults.get(cult_id)
|
|
||||||
.ok_or_else(|| anyhow!("No cult exists for ID `{cult_id}`"))?
|
|
||||||
.clone(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(persons)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
And so, performing a [GraphQL query which lead to N+1 problem](n_plus_1.md)
|
|
||||||
```graphql
|
|
||||||
query {
|
|
||||||
persons {
|
|
||||||
id
|
|
||||||
name
|
|
||||||
cult {
|
|
||||||
id
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
will lead to efficient [SQL] queries, just as expected:
|
|
||||||
```sql
|
|
||||||
SELECT id, name, cult_id FROM persons;
|
|
||||||
SELECT id, name FROM cults WHERE id IN (1, 2, 3, 4);
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## More features
|
|
||||||
|
|
||||||
See more available look-ahead features in the API docs of the [`LookAheadSelection`][21] and the [`LookAheadChildren`][22].
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[`DefaultScalarValue`]: https://docs.rs/juniper/0.16.1/juniper/enum.DefaultScalarValue.html
|
|
||||||
[`Executor`]: https://docs.rs/juniper/0.16.1/juniper/executor/struct.Executor.html
|
|
||||||
[`ScalarValue`]: https://docs.rs/juniper/0.16.1/juniper/trait.ScalarValue.html
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
[SQL]: https://en.wikipedia.org/wiki/SQL
|
|
||||||
|
|
||||||
[1]: https://spec.graphql.org/October2021#sec-Execution
|
|
||||||
[2]: https://spec.graphql.org/October2021#sec-Language.Operations\
|
|
||||||
[3]: https://spec.graphql.org/October2021#sec-Language.Fields
|
|
||||||
[20]: https://docs.rs/juniper/0.16.1/juniper/executor/struct.Executor.html#method.look_ahead
|
|
||||||
[21]: https://docs.rs/juniper/0.16.1/juniper/executor/struct.LookAheadSelection.html
|
|
||||||
[22]: https://docs.rs/juniper/0.16.1/juniper/executor/struct.LookAheadChildren.html
|
|
|
@ -1,111 +0,0 @@
|
||||||
N+1 problem
|
|
||||||
===========
|
|
||||||
|
|
||||||
A common issue with [GraphQL] server implementations is how the [resolvers][2] query their datasource. With a naive and straightforward approach we quickly run into the N+1 problem, resulting in a large number of unnecessary database queries or [HTTP] requests.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# extern crate anyhow;
|
|
||||||
# extern crate juniper;
|
|
||||||
# use anyhow::anyhow;
|
|
||||||
# use juniper::{graphql_object, GraphQLObject};
|
|
||||||
#
|
|
||||||
# type CultId = i32;
|
|
||||||
# type UserId = i32;
|
|
||||||
#
|
|
||||||
# struct Repository;
|
|
||||||
#
|
|
||||||
# impl juniper::Context for Repository {}
|
|
||||||
#
|
|
||||||
# impl Repository {
|
|
||||||
# async fn load_cult_by_id(&self, cult_id: CultId) -> anyhow::Result<Option<Cult>> { unimplemented!() }
|
|
||||||
# async fn load_all_persons(&self) -> anyhow::Result<Vec<Person>> { unimplemented!() }
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Cult {
|
|
||||||
id: CultId,
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Person {
|
|
||||||
id: UserId,
|
|
||||||
name: String,
|
|
||||||
cult_id: CultId,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(context = Repository)]
|
|
||||||
impl Person {
|
|
||||||
fn id(&self) -> CultId {
|
|
||||||
self.id
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
self.name.as_str()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn cult(&self, #[graphql(ctx)] repo: &Repository) -> anyhow::Result<Cult> {
|
|
||||||
// Effectively performs the following SQL query:
|
|
||||||
// SELECT id, name FROM cults WHERE id = ${cult_id} LIMIT 1
|
|
||||||
repo.load_cult_by_id(self.cult_id)
|
|
||||||
.await?
|
|
||||||
.ok_or_else(|| anyhow!("No cult exists for ID `{}`", self.cult_id))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Query;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(context = Repository)]
|
|
||||||
impl Query {
|
|
||||||
async fn persons(#[graphql(ctx)] repo: &Repository) -> anyhow::Result<Vec<Person>> {
|
|
||||||
// Effectively performs the following SQL query:
|
|
||||||
// SELECT id, name, cult_id FROM persons
|
|
||||||
repo.load_all_persons().await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Let's say we want to list a bunch of `cult`s `persons` were in:
|
|
||||||
```graphql
|
|
||||||
query {
|
|
||||||
persons {
|
|
||||||
id
|
|
||||||
name
|
|
||||||
cult {
|
|
||||||
id
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Once the `persons` [list][1] has been [resolved][2], a separate [SQL] query is run to find the `cult` of each `Person`. We can see how this could quickly become a problem.
|
|
||||||
```sql
|
|
||||||
SELECT id, name, cult_id FROM persons;
|
|
||||||
SELECT id, name FROM cults WHERE id = 1;
|
|
||||||
SELECT id, name FROM cults WHERE id = 2;
|
|
||||||
SELECT id, name FROM cults WHERE id = 1;
|
|
||||||
SELECT id, name FROM cults WHERE id = 3;
|
|
||||||
SELECT id, name FROM cults WHERE id = 4;
|
|
||||||
SELECT id, name FROM cults WHERE id = 1;
|
|
||||||
SELECT id, name FROM cults WHERE id = 2;
|
|
||||||
-- and so on...
|
|
||||||
```
|
|
||||||
|
|
||||||
There are several ways how this problem may be resolved in [Juniper]. The most common ones are:
|
|
||||||
- [DataLoader](dataloader.md)
|
|
||||||
- [Look-ahead machinery](lookahead.md)
|
|
||||||
- [Eager loading](eager_loading.md)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[HTTP]: https://en.wikipedia.org/wiki/HTTP
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
[SQL]: https://en.wikipedia.org/wiki/SQL
|
|
||||||
|
|
||||||
[1]: https://spec.graphql.org/October2021#sec-List
|
|
||||||
[2]: https://spec.graphql.org/October2021#sec-Executing-Fields
|
|
|
@ -1,85 +0,0 @@
|
||||||
Introduction
|
|
||||||
============
|
|
||||||
|
|
||||||
> [GraphQL] is a query language for APIs and a runtime for fulfilling those queries with your existing data. [GraphQL] provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
|
|
||||||
|
|
||||||
[Juniper] is a library for creating [GraphQL] servers in [Rust]. Build type-safe and fast API servers with minimal boilerplate and configuration (we do try to make declaring and resolving [GraphQL] schemas as convenient as [Rust] will allow).
|
|
||||||
|
|
||||||
[Juniper] doesn't include a web server itself, instead, it provides building blocks to make integration with existing web servers straightforward. It optionally provides a pre-built integration for some widely used web server frameworks in [Rust] ecosystem.
|
|
||||||
|
|
||||||
- [Cargo crate](https://crates.io/crates/juniper)
|
|
||||||
- [API reference][`juniper`]
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
[Juniper] supports the full GraphQL query language according to the [specification (October 2021)][GraphQL spec].
|
|
||||||
|
|
||||||
> **NOTE**: As an exception to other [GraphQL] libraries for other languages, [Juniper] builds non-`null` types by default. A field of type `Vec<Episode>` will be converted into `[Episode!]!`. The corresponding Rust type for a `null`able `[Episode]` would be `Option<Vec<Option<Episode>>>` instead.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Integrations
|
|
||||||
|
|
||||||
|
|
||||||
### Types
|
|
||||||
|
|
||||||
[Juniper] provides out-of-the-box integration for some very common [Rust] crates to make building schemas a breeze. The types from these crates will be usable in your schemas automatically after enabling the correspondent self-titled [Cargo feature]:
|
|
||||||
- [`bigdecimal`]
|
|
||||||
- [`bson`]
|
|
||||||
- [`chrono`], [`chrono-tz`]
|
|
||||||
- [`jiff`]
|
|
||||||
- [`rust_decimal`]
|
|
||||||
- [`time`]
|
|
||||||
- [`url`]
|
|
||||||
- [`uuid`]
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### Web server frameworks
|
|
||||||
|
|
||||||
- [`actix-web`] ([`juniper_actix`] crate)
|
|
||||||
- [`axum`] ([`juniper_axum`] crate)
|
|
||||||
- [`hyper`] ([`juniper_hyper`] crate)
|
|
||||||
- [`rocket`] ([`juniper_rocket`] crate)
|
|
||||||
- [`warp`] ([`juniper_warp`] crate)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## API stability
|
|
||||||
|
|
||||||
[Juniper] has not reached 1.0 yet, thus some API instability should be expected.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[`actix-web`]: https://docs.rs/actix-web
|
|
||||||
[`axum`]: https://docs.rs/axum
|
|
||||||
[`bigdecimal`]: https://docs.rs/bigdecimal
|
|
||||||
[`bson`]: https://docs.rs/bson
|
|
||||||
[`chrono`]: https://docs.rs/chrono
|
|
||||||
[`chrono-tz`]: https://docs.rs/chrono-tz
|
|
||||||
[`jiff`]: https://docs.rs/jiff
|
|
||||||
[`juniper`]: https://docs.rs/juniper
|
|
||||||
[`juniper_actix`]: https://docs.rs/juniper_actix
|
|
||||||
[`juniper_axum`]: https://docs.rs/juniper_axum
|
|
||||||
[`juniper_hyper`]: https://docs.rs/juniper_hyper
|
|
||||||
[`juniper_rocket`]: https://docs.rs/juniper_rocket
|
|
||||||
[`juniper_warp`]: https://docs.rs/juniper_warp
|
|
||||||
[`hyper`]: https://docs.rs/hyper
|
|
||||||
[`rocket`]: https://docs.rs/rocket
|
|
||||||
[`rust_decimal`]: https://docs.rs/rust_decimal
|
|
||||||
[`time`]: https://docs.rs/time
|
|
||||||
[`url`]: https://docs.rs/url
|
|
||||||
[`uuid`]: https://docs.rs/uuid
|
|
||||||
[`warp`]: https://docs.rs/warp
|
|
||||||
[Cargo feature]: https://doc.rust-lang.org/cargo/reference/features.html
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[GraphQL spec]: https://spec.graphql.org/October2021
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
|
@ -1,232 +0,0 @@
|
||||||
Quickstart
|
|
||||||
==========
|
|
||||||
|
|
||||||
This page will give you a short introduction to the concepts in [Juniper].
|
|
||||||
|
|
||||||
**[Juniper] follows a [code-first] approach to define a [GraphQL] schema.**
|
|
||||||
|
|
||||||
> **TIP**: For a [schema-first] approach, consider using a [`juniper-from-schema`] crate for generating a [`juniper`]-based code from a [schema] file.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Installation
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies]
|
|
||||||
juniper = "0.16.1"
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Schema
|
|
||||||
|
|
||||||
Exposing simple enums and structs as [GraphQL] types is just a matter of adding a custom [derive attribute] to them. [Juniper] includes support for basic [Rust] types that naturally map to [GraphQL] features, such as `Option<T>`, `Vec<T>`, `Box<T>`, `Arc<T>`, `String`, `f64`, `i32`, references, slices and arrays.
|
|
||||||
|
|
||||||
For more advanced mappings, [Juniper] provides multiple macros to map your [Rust] types to a [GraphQL schema][schema]. The most important one is the [`#[graphql_object]` attribute][2] that is used for declaring a [GraphQL object] with resolvers (typically used for declaring [`Query` and `Mutation` roots][1]).
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# # ![allow(unused_variables)]
|
|
||||||
# extern crate juniper;
|
|
||||||
#
|
|
||||||
# use std::fmt::Display;
|
|
||||||
#
|
|
||||||
use juniper::{
|
|
||||||
graphql_object, EmptySubscription, FieldResult, GraphQLEnum,
|
|
||||||
GraphQLInputObject, GraphQLObject, ScalarValue,
|
|
||||||
};
|
|
||||||
#
|
|
||||||
# struct DatabasePool;
|
|
||||||
# impl DatabasePool {
|
|
||||||
# fn get_connection(&self) -> FieldResult<DatabasePool> { Ok(DatabasePool) }
|
|
||||||
# fn find_human(&self, _id: &str) -> FieldResult<Human> { Err("")? }
|
|
||||||
# fn insert_human(&self, _human: &NewHuman) -> FieldResult<Human> { Err("")? }
|
|
||||||
# }
|
|
||||||
|
|
||||||
#[derive(GraphQLEnum)]
|
|
||||||
enum Episode {
|
|
||||||
NewHope,
|
|
||||||
Empire,
|
|
||||||
Jedi,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
#[graphql(description = "A humanoid creature in the Star Wars universe")]
|
|
||||||
struct Human {
|
|
||||||
id: String,
|
|
||||||
name: String,
|
|
||||||
appears_in: Vec<Episode>,
|
|
||||||
home_planet: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
// There is also a custom derive for mapping GraphQL input objects.
|
|
||||||
#[derive(GraphQLInputObject)]
|
|
||||||
#[graphql(description = "A humanoid creature in the Star Wars universe")]
|
|
||||||
struct NewHuman {
|
|
||||||
name: String,
|
|
||||||
appears_in: Vec<Episode>,
|
|
||||||
home_planet: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Now, we create our root `Query` and `Mutation` types with resolvers by using
|
|
||||||
// the `#[graphql_object]` attribute.
|
|
||||||
|
|
||||||
// Resolvers can have a context that allows accessing shared state like a
|
|
||||||
// database pool.
|
|
||||||
struct Context {
|
|
||||||
// Use your real database pool here.
|
|
||||||
db: DatabasePool,
|
|
||||||
}
|
|
||||||
|
|
||||||
// To make our `Context` usable by `juniper`, we have to implement a marker
|
|
||||||
// trait.
|
|
||||||
impl juniper::Context for Context {}
|
|
||||||
|
|
||||||
struct Query;
|
|
||||||
|
|
||||||
// Here we specify the context type for the object.
|
|
||||||
// We need to do this in every type that needs access to the `Context`.
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(context = Context)]
|
|
||||||
impl Query {
|
|
||||||
// Note, that the field name will be automatically converted to the
|
|
||||||
// `camelCased` variant, just as GraphQL conventions imply.
|
|
||||||
fn api_version() -> &'static str {
|
|
||||||
"1.0"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn human(
|
|
||||||
// Arguments to resolvers can either be simple scalar types, enums or
|
|
||||||
// input objects.
|
|
||||||
id: String,
|
|
||||||
// To gain access to the `Context`, we specify a `context`-named
|
|
||||||
// argument referring the correspondent `Context` type, and `juniper`
|
|
||||||
// will inject it automatically.
|
|
||||||
context: &Context,
|
|
||||||
) -> FieldResult<Human> {
|
|
||||||
// Get a `db` connection.
|
|
||||||
let conn = context.db.get_connection()?;
|
|
||||||
// Execute a `db` query.
|
|
||||||
// Note the use of `?` to propagate errors.
|
|
||||||
let human = conn.find_human(&id)?;
|
|
||||||
// Return the result.
|
|
||||||
Ok(human)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Now, we do the same for our `Mutation` type.
|
|
||||||
|
|
||||||
struct Mutation;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(
|
|
||||||
context = Context,
|
|
||||||
// If we need to use `ScalarValue` parametrization explicitly somewhere
|
|
||||||
// in the object definition (like here in `FieldResult`), we could
|
|
||||||
// declare an explicit type parameter for that, and specify it.
|
|
||||||
scalar = S: ScalarValue + Display,
|
|
||||||
)]
|
|
||||||
impl Mutation {
|
|
||||||
fn create_human<S: ScalarValue + Display>(
|
|
||||||
new_human: NewHuman,
|
|
||||||
context: &Context,
|
|
||||||
) -> FieldResult<Human, S> {
|
|
||||||
let db = context.db.get_connection().map_err(|e| e.map_scalar_value())?;
|
|
||||||
let human: Human = db.insert_human(&new_human).map_err(|e| e.map_scalar_value())?;
|
|
||||||
Ok(human)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Root schema consists of a query, a mutation, and a subscription.
|
|
||||||
// Request queries can be executed against a `RootNode`.
|
|
||||||
type Schema = juniper::RootNode<'static, Query, Mutation, EmptySubscription<Context>>;
|
|
||||||
#
|
|
||||||
# fn main() {
|
|
||||||
# _ = Schema::new(Query, Mutation, EmptySubscription::new());
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Now we have a very simple but functional schema for a [GraphQL] server!
|
|
||||||
|
|
||||||
To actually serve the [schema], see the guides for our various [server integrations](serve/index.md).
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Execution
|
|
||||||
|
|
||||||
[Juniper] is a library that can be used in many contexts: it doesn't require a server, nor it has a dependency on a particular transport or serialization format. You can invoke the `juniper::execute()` directly to get a result for a [GraphQL] query:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# // Only needed due to 2018 edition because the macro is not accessible.
|
|
||||||
# #[macro_use] extern crate juniper;
|
|
||||||
use juniper::{
|
|
||||||
graphql_object, graphql_value, EmptyMutation, EmptySubscription,
|
|
||||||
GraphQLEnum, Variables,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(GraphQLEnum, Clone, Copy)]
|
|
||||||
enum Episode {
|
|
||||||
// Note, that the enum value will be automatically converted to the
|
|
||||||
// `SCREAMING_SNAKE_CASE` variant, just as GraphQL conventions imply.
|
|
||||||
NewHope,
|
|
||||||
Empire,
|
|
||||||
Jedi,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Arbitrary context data.
|
|
||||||
struct Ctx(Episode);
|
|
||||||
|
|
||||||
impl juniper::Context for Ctx {}
|
|
||||||
|
|
||||||
struct Query;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(context = Ctx)]
|
|
||||||
impl Query {
|
|
||||||
fn favorite_episode(context: &Ctx) -> Episode {
|
|
||||||
context.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Schema = juniper::RootNode<'static, Query, EmptyMutation<Ctx>, EmptySubscription<Ctx>>;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
// Create a context.
|
|
||||||
let ctx = Ctx(Episode::NewHope);
|
|
||||||
|
|
||||||
// Run the execution.
|
|
||||||
let (res, _errors) = juniper::execute_sync(
|
|
||||||
"query { favoriteEpisode }",
|
|
||||||
None,
|
|
||||||
&Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()),
|
|
||||||
&Variables::new(),
|
|
||||||
&ctx,
|
|
||||||
).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
res,
|
|
||||||
graphql_value!({
|
|
||||||
"favoriteEpisode": "NEW_HOPE",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[`juniper`]: https://docs.rs/juniper
|
|
||||||
[`juniper-from-schema`]: https://docs.rs/juniper-from-schema
|
|
||||||
[code-first]: https://www.apollographql.com/blog/backend/architecture/schema-first-vs-code-only-graphql#code-only
|
|
||||||
[derive attribute]: https://doc.rust-lang.org/stable/reference/attributes/derive.html#derive
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[GraphQL object]: https://spec.graphql.org/October2021#sec-Objects
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
[schema]: https://graphql.org/learn/schema
|
|
||||||
[schema-first]: https://www.apollographql.com/blog/backend/architecture/schema-first-vs-code-only-graphql#schema-first
|
|
||||||
|
|
||||||
[1]: https://spec.graphql.org/October2021#sec-Root-Operation-Types
|
|
||||||
[2]: https://docs.rs/juniper/0.16.1/juniper/macro.graphql_object.html
|
|
|
@ -1,185 +0,0 @@
|
||||||
Schema
|
|
||||||
======
|
|
||||||
|
|
||||||
**[Juniper] follows a [code-first] approach to define a [GraphQL] schema.**
|
|
||||||
|
|
||||||
> **TIP**: For a [schema-first] approach, consider using a [`juniper-from-schema`] crate for generating a [`juniper`]-based code from a [schema] file.
|
|
||||||
|
|
||||||
[GraphQL schema][0] consists of three [object types][4]: a [query root][1], a [mutation root][2], and a [subscription root][3].
|
|
||||||
|
|
||||||
> The **query** root operation type must be provided and must be an [Object][4] type.
|
|
||||||
>
|
|
||||||
> The **mutation** root operation type is optional; if it is not provided, the service does not support mutations. If it is provided, it must be an [Object][4] type.
|
|
||||||
>
|
|
||||||
> Similarly, the **subscription** root operation type is also optional; if it is not provided, the service does not support subscriptions. If it is provided, it must be an [Object][4] type.
|
|
||||||
>
|
|
||||||
> The **query**, **mutation**, and **subscription** root types must all be different types if provided.
|
|
||||||
|
|
||||||
In [Juniper], the [`RootNode`] type represents a [schema][0]. When the [schema][0] is first created, [Juniper] will traverse the entire object graph and register all types it can find. This means that if we [define a GraphQL object](../types/objects/index.md) somewhere but never use or reference it, it won't be exposed in a [GraphQL schema][0].
|
|
||||||
|
|
||||||
Both [query][1] and [mutation][2] objects are regular [GraphQL objects][4], defined like [any other object in Juniper](../types/objects/index.md). The [mutation][2] and [subscription][3] objects, however, are optional, since [schemas][0] can be read-only and do not require [subscriptions][3].
|
|
||||||
|
|
||||||
> **TIP**: If [mutation][2]/[subscription][3] functionality is not needed, consider using the predefined [`EmptyMutation`]/[`EmptySubscription`] types for stubbing them in a [`RootNode`].
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{
|
|
||||||
# graphql_object, EmptySubscription, FieldResult, GraphQLObject, RootNode,
|
|
||||||
# };
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct User {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Query;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Query {
|
|
||||||
fn user_with_username(username: String) -> FieldResult<Option<User>> {
|
|
||||||
// Look up user in database...
|
|
||||||
# unimplemented!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Mutation;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Mutation {
|
|
||||||
fn sign_up_user(name: String, email: String) -> FieldResult<User> {
|
|
||||||
// Validate inputs and save user in database...
|
|
||||||
# unimplemented!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Schema = RootNode<'static, Query, Mutation, EmptySubscription>;
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **NOTE**: It's considered a [good practice][5] to name [query][1], [mutation][2], and [subscription][3] root types as `Query`, `Mutation`, and `Subscription` respectively.
|
|
||||||
|
|
||||||
The usage of [subscriptions][3] is a little different from the [mutation][2] and [query][1] [objects][4], so they are discussed in the [separate chapter](subscriptions.md).
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Export
|
|
||||||
|
|
||||||
Many tools in [GraphQL] ecosystem require a [schema] definition to operate on. With [Juniper] we can export our [GraphQL schema][0] defined in [Rust] code either represented in the [GraphQL schema language][6] or in [JSON].
|
|
||||||
|
|
||||||
|
|
||||||
### SDL (schema definition language)
|
|
||||||
|
|
||||||
To generate an [SDL (schema definition language)][6] representation of a [GraphQL schema][0] defined in [Rust] code, the [`as_sdl()` method][20] should be used for the direct extraction (requires enabling the `schema-language` [Juniper] feature):
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{
|
|
||||||
# graphql_object, EmptyMutation, EmptySubscription, FieldResult, RootNode,
|
|
||||||
# };
|
|
||||||
#
|
|
||||||
struct Query;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Query {
|
|
||||||
fn hello(&self) -> FieldResult<&str> {
|
|
||||||
Ok("hello world")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
// Define our schema in Rust.
|
|
||||||
let schema = RootNode::new(
|
|
||||||
Query,
|
|
||||||
EmptyMutation::<()>::new(),
|
|
||||||
EmptySubscription::<()>::new(),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Convert the Rust schema into the GraphQL SDL schema.
|
|
||||||
let result = schema.as_sdl();
|
|
||||||
|
|
||||||
let expected = "\
|
|
||||||
schema {
|
|
||||||
query: Query
|
|
||||||
}
|
|
||||||
|
|
||||||
type Query {
|
|
||||||
hello: String!
|
|
||||||
}
|
|
||||||
";
|
|
||||||
# #[cfg(not(target_os = "windows"))]
|
|
||||||
assert_eq!(result, expected);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### JSON
|
|
||||||
|
|
||||||
To export a [GraphQL schema][0] defined in [Rust] code as [JSON] (often referred to as `schema.json`), the specially crafted [introspection query][21] should be issued. [Juniper] provides a [convenience `introspect()` function][22] to [introspect](introspection.md) the entire [schema][0], which result can be serialized into [JSON]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# extern crate serde_json;
|
|
||||||
# use juniper::{
|
|
||||||
# graphql_object, EmptyMutation, EmptySubscription, GraphQLObject,
|
|
||||||
# IntrospectionFormat, RootNode,
|
|
||||||
# };
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Example {
|
|
||||||
id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Query;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Query {
|
|
||||||
fn example(id: String) -> Example {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Schema = RootNode<'static, Query, EmptyMutation, EmptySubscription>;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
// Run the built-in introspection query.
|
|
||||||
let (res, _errors) = juniper::introspect(
|
|
||||||
&Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()),
|
|
||||||
&(),
|
|
||||||
IntrospectionFormat::default(),
|
|
||||||
).unwrap();
|
|
||||||
|
|
||||||
// Serialize the introspection result into JSON.
|
|
||||||
let json_result = serde_json::to_string_pretty(&res);
|
|
||||||
assert!(json_result.is_ok());
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **TIP**: We still can convert the generated [JSON] into a [GraphQL schema language][6] representation by using tools like [`graphql-json-to-sdl` command line utility][30].
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[`EmptyMutation`]: https://docs.rs/juniper/0.16.1/juniper/struct.EmptyMutation.html
|
|
||||||
[`EmptySubscription`]: https://docs.rs/juniper/0.16.1/juniper/struct.EmptySubscription.html
|
|
||||||
[`juniper`]: https://docs.rs/juniper
|
|
||||||
[`juniper-from-schema`]: https://docs.rs/juniper-from-schema
|
|
||||||
[`RootNode`]: https://docs.rs/juniper/0.16.1/juniper/struct.RootNode.html
|
|
||||||
[code-first]: https://www.apollographql.com/blog/backend/architecture/schema-first-vs-code-only-graphql#code-only
|
|
||||||
[schema-first]: https://www.apollographql.com/blog/backend/architecture/schema-first-vs-code-only-graphql#schema-first
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[JSON]: https://www.json.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
[schema]: https://graphql.org/learn/schema
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Schema
|
|
||||||
[1]: https://spec.graphql.org/October2021#sel-FAHTRFCAACChCtpG
|
|
||||||
[2]: https://spec.graphql.org/October2021#sel-FAHTRHCAACCuE9yD
|
|
||||||
[3]: https://spec.graphql.org/October2021#sel-FAHTRJCAACC3EhsX
|
|
||||||
[4]: https://spec.graphql.org/October2021#sec-Objects
|
|
||||||
[5]: https://spec.graphql.org/October2021#sec-Root-Operation-Types.Default-Root-Operation-Type-Names
|
|
||||||
[6]: https://graphql.org/learn/schema#type-language
|
|
||||||
[20]: https://docs.rs/juniper/0.16.1/juniper/struct.RootNode.html#method.as_sdl
|
|
||||||
[21]: https://docs.rs/crate/juniper/latest/source/src/introspection/query.graphql
|
|
||||||
[22]: https://docs.rs/juniper/0.16.1/juniper/fn.introspect.html
|
|
||||||
[30]: https://npmjs.com/package/graphql-json-to-sdl
|
|
|
@ -1,83 +0,0 @@
|
||||||
Introspection
|
|
||||||
=============
|
|
||||||
|
|
||||||
> The [schema introspection][1] system is accessible from the meta-fields `__schema` and `__type` which are accessible from the type of the root of a query operation.
|
|
||||||
> ```graphql
|
|
||||||
> __schema: __Schema!
|
|
||||||
> __type(name: String!): __Type
|
|
||||||
> ```
|
|
||||||
> Like all meta-fields, these are implicit and do not appear in the fields list in the root type of the query operation.
|
|
||||||
|
|
||||||
[GraphQL] provides [introspection][0], allowing to see what [queries][2], [mutations][3] and [subscriptions][4] a [GraphQL] server supports at runtime.
|
|
||||||
|
|
||||||
Because [introspection][0] queries are just regular [GraphQL queries][2], [Juniper] supports them natively. For example, to get all the names of the types supported, we could [execute][5] the following [query][2] against [Juniper]:
|
|
||||||
```graphql
|
|
||||||
{
|
|
||||||
__schema {
|
|
||||||
types {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Disabling
|
|
||||||
|
|
||||||
> Disabling introspection in production is a widely debated topic, but we believe it’s one of the first things you can do to harden your GraphQL API in production.
|
|
||||||
|
|
||||||
[Some security requirements and considerations][10] may mandate to disable [GraphQL schema introspection][1] in production environments. In [Juniper] this can be achieved by using the [`RootNode::disable_introspection()`][9] method:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{
|
|
||||||
# graphql_object, graphql_vars, EmptyMutation, EmptySubscription, GraphQLError,
|
|
||||||
# RootNode,
|
|
||||||
# };
|
|
||||||
#
|
|
||||||
pub struct Query;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Query {
|
|
||||||
fn some() -> bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Schema = RootNode<'static, Query, EmptyMutation, EmptySubscription>;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new())
|
|
||||||
.disable_introspection();
|
|
||||||
|
|
||||||
let query = "query { __schema { queryType { name } } }";
|
|
||||||
|
|
||||||
match juniper::execute_sync(query, None, &schema, &graphql_vars! {}, &()) {
|
|
||||||
Err(GraphQLError::ValidationError(errs)) => {
|
|
||||||
assert_eq!(
|
|
||||||
errs.first().unwrap().message(),
|
|
||||||
"GraphQL introspection is not allowed, but the operation contained `__schema`",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
res => panic!("expected `ValidationError`, returned: {res:#?}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
> **NOTE**: Attempt to execute an [introspection query][1] results in [validation][11] error, rather than [execution][5] error.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Introspection
|
|
||||||
[1]: https://spec.graphql.org/October2021#sec-Schema-Introspection
|
|
||||||
[2]: https://spec.graphql.org/October2021#sel-GAFRJBABABF_jB
|
|
||||||
[3]: https://spec.graphql.org/October2021#sel-GAFRJDABABI5C
|
|
||||||
[4]: https://spec.graphql.org/October2021#sel-GAFRJFABABMvpN
|
|
||||||
[5]: https://spec.graphql.org/October2021#sec-Execution
|
|
||||||
[9]: https://docs.rs/juniper/0.16.1/juniper/struct.RootNode.html#method.disable_introspection
|
|
||||||
[10]: https://www.apollographql.com/blog/why-you-should-disable-graphql-introspection-in-production
|
|
||||||
[11]: https://spec.graphql.org/October2021#sec-Validation
|
|
|
@ -1,176 +0,0 @@
|
||||||
Subscriptions
|
|
||||||
=============
|
|
||||||
|
|
||||||
[GraphQL subscriptions][9] are a way to push data from a server to clients requesting real-time messages from a server. [Subscriptions][9] are similar to [queries][7] in that they specify a set of fields to be delivered to a client, but instead of immediately returning a single answer a result is sent every time a particular event happens on a server.
|
|
||||||
|
|
||||||
In order to execute [subscriptions][9] in [Juniper], we need a coordinator (spawning long-lived connections) and a [GraphQL object][4] with [fields][5] resolving into a [`Stream`] of elements which will then be returned to a client. The [`juniper_subscriptions` crate][30] provides a default implementation of these abstractions.
|
|
||||||
|
|
||||||
The [subscription root][3] is just a [GraphQL object][4], similar to the [query root][1] and [mutations root][2] that we define for operations in our [GraphQL schema][0]. For [subscriptions][9] all fields should be `async` and return a [`Stream`] of some [GraphQL type][6] values, rather than direct values.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# extern crate futures;
|
|
||||||
# extern crate juniper;
|
|
||||||
# use std::pin::Pin;
|
|
||||||
# use futures::Stream;
|
|
||||||
# use juniper::{graphql_object, graphql_subscription, FieldError};
|
|
||||||
#
|
|
||||||
# #[derive(Clone)]
|
|
||||||
# pub struct Database;
|
|
||||||
#
|
|
||||||
# impl juniper::Context for Database {}
|
|
||||||
#
|
|
||||||
# pub struct Query;
|
|
||||||
#
|
|
||||||
# #[graphql_object]
|
|
||||||
# #[graphql(context = Database)]
|
|
||||||
# impl Query {
|
|
||||||
# fn hello_world() -> &'static str {
|
|
||||||
# "Hello World!"
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
type StringStream = Pin<Box<dyn Stream<Item = Result<String, FieldError>> + Send>>;
|
|
||||||
|
|
||||||
pub struct Subscription;
|
|
||||||
|
|
||||||
#[graphql_subscription]
|
|
||||||
#[graphql(context = Database)]
|
|
||||||
impl Subscription {
|
|
||||||
// This subscription operation emits two values sequentially:
|
|
||||||
// the `String`s "Hello" and "World!".
|
|
||||||
async fn hello_world() -> StringStream {
|
|
||||||
let stream = futures::stream::iter([
|
|
||||||
Ok(String::from("Hello")),
|
|
||||||
Ok(String::from("World!")),
|
|
||||||
]);
|
|
||||||
Box::pin(stream)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main () {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Coordinator
|
|
||||||
|
|
||||||
[GraphQL subscriptions][9] require a bit more resources than regular [queries][7] and provide a great vector for [DoS attacks][20]. This can can bring down a server easily if not handled correctly. The [`SubscriptionCoordinator` trait][`SubscriptionCoordinator`] provides coordination logic to enable functionality like [DoS attacks][20] mitigation and resource limits.
|
|
||||||
|
|
||||||
The [`SubscriptionCoordinator`] contains the [schema][0] and can keep track of opened connections, handle [subscription][9] start and end, and maintain a global ID for each [subscription][9]. Each time a connection is established, the [`SubscriptionCoordinator`] spawns a [32], which handles a single connection, providing resolver logic for a client stream as well as reconnection and shutdown logic.
|
|
||||||
|
|
||||||
While we can implement [`SubscriptionCoordinator`] ourselves, [Juniper] contains a simple and generic implementation called [`Coordinator`]. The `subscribe` method returns a [`Future`] resolving into a `Result<Connection, GraphQLError>`, where [`Connection`] is a [`Stream`] of [values][10] returned by the operation, and a [`GraphQLError`] is the error when the [subscription operation][9] fails.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# extern crate futures;
|
|
||||||
# extern crate juniper;
|
|
||||||
# extern crate juniper_subscriptions;
|
|
||||||
# extern crate serde_json;
|
|
||||||
# use std::pin::Pin;
|
|
||||||
# use futures::{Stream, StreamExt as _};
|
|
||||||
# use juniper::{
|
|
||||||
# http::GraphQLRequest,
|
|
||||||
# graphql_object, graphql_subscription,
|
|
||||||
# DefaultScalarValue, EmptyMutation, FieldError,
|
|
||||||
# RootNode, SubscriptionCoordinator,
|
|
||||||
# };
|
|
||||||
# use juniper_subscriptions::Coordinator;
|
|
||||||
#
|
|
||||||
# #[derive(Clone)]
|
|
||||||
# pub struct Database;
|
|
||||||
#
|
|
||||||
# impl juniper::Context for Database {}
|
|
||||||
#
|
|
||||||
# impl Database {
|
|
||||||
# fn new() -> Self {
|
|
||||||
# Self
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
# pub struct Query;
|
|
||||||
#
|
|
||||||
# #[graphql_object]
|
|
||||||
# #[graphql(context = Database)]
|
|
||||||
# impl Query {
|
|
||||||
# fn hello_world() -> &'static str {
|
|
||||||
# "Hello World!"
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
# type StringStream = Pin<Box<dyn Stream<Item = Result<String, FieldError>> + Send>>;
|
|
||||||
#
|
|
||||||
# pub struct Subscription;
|
|
||||||
#
|
|
||||||
# #[graphql_subscription]
|
|
||||||
# #[graphql(context = Database)]
|
|
||||||
# impl Subscription {
|
|
||||||
# async fn hello_world() -> StringStream {
|
|
||||||
# let stream = futures::stream::iter([
|
|
||||||
# Ok(String::from("Hello")),
|
|
||||||
# Ok(String::from("World!")),
|
|
||||||
# ]);
|
|
||||||
# Box::pin(stream)
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
type Schema = RootNode<'static, Query, EmptyMutation<Database>, Subscription>;
|
|
||||||
|
|
||||||
fn schema() -> Schema {
|
|
||||||
Schema::new(Query, EmptyMutation::new(), Subscription)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn run_subscription() {
|
|
||||||
let schema = schema();
|
|
||||||
let coordinator = Coordinator::new(schema);
|
|
||||||
let db = Database::new();
|
|
||||||
|
|
||||||
let req: GraphQLRequest<DefaultScalarValue> = serde_json::from_str(
|
|
||||||
r#"{
|
|
||||||
"query": "subscription { helloWorld }"
|
|
||||||
}"#,
|
|
||||||
).unwrap();
|
|
||||||
|
|
||||||
let mut conn = coordinator.subscribe(&req, &db).await.unwrap();
|
|
||||||
while let Some(result) = conn.next().await {
|
|
||||||
println!("{}", serde_json::to_string(&result).unwrap());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## WebSocket
|
|
||||||
|
|
||||||
For information about serving [GraphQL subscriptions][9] over [WebSocket], see the ["Serving" chapter](../serve/index.md#websocket).
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[`Coordinator`]: https://docs.rs/juniper_subscriptions/0.17.0/juniper_subscriptions/struct.Coordinator.html
|
|
||||||
[`Connection`]: https://docs.rs/juniper_subscriptions/0.17.0/juniper_subscriptions/struct.Connection.html
|
|
||||||
[`Future`]: https://doc.rust-lang.org/stable/std/future/trait.Future.html
|
|
||||||
[`GraphQLError`]: https://docs.rs/juniper/0.16.1/juniper/enum.GraphQLError.html
|
|
||||||
[`Stream`]: https://docs.rs/futures/latest/futures/stream/trait.Stream.html
|
|
||||||
[`SubscriptionCoordinator`]: https://docs.rs/juniper/0.16.1/juniper/trait.SubscriptionCoordinator.html
|
|
||||||
[`SubscriptionConnection`]: https://docs.rs/juniper/0.16.1/juniper/trait.SubscriptionConnection.html
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
[WebSocket]: https://en.wikipedia.org/wiki/WebSocket
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Schema
|
|
||||||
[1]: https://spec.graphql.org/October2021#sel-FAHTRFCAACChCtpG
|
|
||||||
[2]: https://spec.graphql.org/October2021#sel-FAHTRHCAACCuE9yD
|
|
||||||
[3]: https://spec.graphql.org/October2021#sel-FAHTRJCAACC3EhsX
|
|
||||||
[4]: https://spec.graphql.org/October2021#sec-Objects
|
|
||||||
[5]: https://spec.graphql.org/October2021#sec-Language.Fields
|
|
||||||
[6]: https://spec.graphql.org/October2021#sec-Types
|
|
||||||
[7]: https://spec.graphql.org/October2021#sec-Query
|
|
||||||
[8]: https://spec.graphql.org/October2021#sec-Mutation
|
|
||||||
[9]: https://spec.graphql.org/October2021#sec-Subscription
|
|
||||||
[10]: https://spec.graphql.org/October2021#sec-Values
|
|
||||||
[20]: https://en.wikipedia.org/wiki/Denial-of-service_attack
|
|
||||||
[30]: https://docs.rs/juniper_subscriptions
|
|
|
@ -1,81 +0,0 @@
|
||||||
Batching
|
|
||||||
========
|
|
||||||
|
|
||||||
The [GraphQL] standard generally assumes that there will be one server request per each client operation to perform (such as a query or mutation). This is conceptually simple but potentially inefficient.
|
|
||||||
|
|
||||||
Some client libraries (such as [`apollo-link-batch-http`][1]) have the ability to batch operations in a single [HTTP] request to save network round-trips and potentially increase performance. There are [some tradeoffs][3], though, that should be considered before [batching operations][2].
|
|
||||||
|
|
||||||
[Juniper]'s [server integration crates](index.md#officially-supported) support [batching multiple operations][2] in a single [HTTP] request out-of-the-box via [JSON] arrays. This makes them compatible with client libraries that support [batch operations][2] without any special configuration.
|
|
||||||
|
|
||||||
> **NOTE**: If you use a custom server integration, it's **not a hard requirement** to support [batching][2], as it's not a part of the [official GraphQL specification][0].
|
|
||||||
|
|
||||||
Assuming an integration supports [operations batching][2], for the following GraphQL query:
|
|
||||||
```graphql
|
|
||||||
{
|
|
||||||
hero {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The [JSON] `data` to [POST] for an individual request would be:
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"query": "{hero{name}}"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
And the response would be in the form:
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"hero": {
|
|
||||||
"name": "R2-D2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
However, if we want to run the same query twice in a single [HTTP] request, the batched [JSON] `data` to [POST] would be:
|
|
||||||
```json
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"query": "{hero{name}}"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"query": "{hero{name}}"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
```
|
|
||||||
And then, the response would be in the following array form:
|
|
||||||
```json
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"hero": {
|
|
||||||
"name": "R2-D2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"hero": {
|
|
||||||
"name": "R2-D2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[HTTP]: https://en.wikipedia.org/wiki/HTTP
|
|
||||||
[JSON]: https://www.json.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[POST]: https://en.wikipedia.org/wiki/POST_(HTTP)
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021
|
|
||||||
[1]: https://www.apollographql.com/docs/link/links/batch-http.html
|
|
||||||
[2]: https://www.apollographql.com/blog/batching-client-graphql-queries
|
|
||||||
[3]: https://www.apollographql.com/blog/batching-client-graphql-queries#what-are-the-tradeoffs-with-batching
|
|
|
@ -1,69 +0,0 @@
|
||||||
Serving
|
|
||||||
=======
|
|
||||||
|
|
||||||
Once we have built a [GraphQL schema][1], the next obvious step would be to serve it, so clients can interact with our [GraphQL] API. Usually, [GraphQL] APIs are served via [HTTP].
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Web server frameworks
|
|
||||||
|
|
||||||
Though the [`juniper`] crate doesn't provide a built-in [HTTP] server, the surrounding ecosystem does.
|
|
||||||
|
|
||||||
|
|
||||||
### Officially supported
|
|
||||||
|
|
||||||
[Juniper] officially supports the following widely used and adopted web server frameworks in [Rust] ecosystem:
|
|
||||||
- [`actix-web`] ([`juniper_actix`] crate)
|
|
||||||
- [`axum`] ([`juniper_axum`] crate)
|
|
||||||
- [`hyper`] ([`juniper_hyper`] crate)
|
|
||||||
- [`rocket`] ([`juniper_rocket`] crate)
|
|
||||||
- [`warp`] ([`juniper_warp`] crate)
|
|
||||||
|
|
||||||
See their API docs and usage examples (accessible from API docs) for further details of how they should be used.
|
|
||||||
|
|
||||||
> **NOTE**: All the officially supported web server framework integrations provide a simple and convenient way for exposing [GraphiQL] and/or [GraphQL Playground] with the [GraphQL schema][1] along. These powerful tools ease the development process by enabling you to explore and send client requests to the [GraphQL] API under development.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## WebSocket
|
|
||||||
|
|
||||||
> **NOTE**: [WebSocket] is a crucial part for serving [GraphQL subscriptions][2] over [HTTP].
|
|
||||||
|
|
||||||
There are two widely adopted protocols for serving [GraphQL] over [WebSocket]:
|
|
||||||
1. [Legacy `graphql-ws` GraphQL over WebSocket Protocol][ws-old], formerly used by [Apollo] and the [`subscriptions-transport-ws` npm package], and now being deprecated.
|
|
||||||
2. [New `graphql-transport-ws` GraphQL over WebSocket Protocol][ws-new], provided by the [`graphql-ws` npm package] and being used by [Apollo] as for now.
|
|
||||||
|
|
||||||
In the [Juniper] ecosystem, both implementations are provided by the [`juniper_graphql_ws`] crate. Most of the [officially supported web server framework integrations](#officially-supported) are able to serve a [GraphQL schema][1] over [WebSocket] (including [subscriptions][2]) and even support [auto-negotiation of the correct protocol based on the `Sec-Websocket-Protocol` HTTP header value][3]. See their API docs and usage examples (accessible from API docs) for further details of how to do so.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[`actix-web`]: https://docs.rs/actix-web
|
|
||||||
[`axum`]: https://docs.rs/axum
|
|
||||||
[`graphql-ws` npm package]: https://npmjs.com/package/graphql-ws
|
|
||||||
[`juniper`]: https://docs.rs/juniper
|
|
||||||
[`juniper_actix`]: https://docs.rs/juniper_actix
|
|
||||||
[`juniper_axum`]: https://docs.rs/juniper_axum
|
|
||||||
[`juniper_graphql_ws`]: https://docs.rs/juniper_graphql_ws
|
|
||||||
[`juniper_rocket`]: https://docs.rs/juniper_rocket
|
|
||||||
[`juniper_warp`]: https://docs.rs/juniper_warp
|
|
||||||
[`hyper`]: https://docs.rs/hyper
|
|
||||||
[`rocket`]: https://docs.rs/rocket
|
|
||||||
[`subscriptions-transport-ws` npm package]: https://npmjs.com/package/subscriptions-transport-ws
|
|
||||||
[`warp`]: https://docs.rs/warp
|
|
||||||
[Apollo]: https://www.apollographql.com
|
|
||||||
[GraphiQL]: https://github.com/graphql/graphiql
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[GraphQL Playground]: https://github.com/prisma/graphql-playground
|
|
||||||
[HTTP]: https://en.wikipedia.org/wiki/HTTP
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
[WebSocket]: https://en.wikipedia.org/wiki/WebSocket
|
|
||||||
[ws-new]: https://github.com/enisdenjo/graphql-ws/blob/v5.14.0/PROTOCOL.md
|
|
||||||
[ws-old]: https://github.com/apollographql/subscriptions-transport-ws/blob/v0.11.0/PROTOCOL.md
|
|
||||||
|
|
||||||
[1]: ../schema/index.md
|
|
||||||
[2]: ../schema/subscriptions.md
|
|
||||||
[3]: https://developer.mozilla.org/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#subprotocols
|
|
|
@ -1,151 +0,0 @@
|
||||||
Enums
|
|
||||||
=====
|
|
||||||
|
|
||||||
> [GraphQL enum][0] types, like [scalar][1] types, also represent leaf values in a GraphQL type system. However [enum][0] types describe the set of possible values.
|
|
||||||
>
|
|
||||||
> [Enums][0] are not references for a numeric value, but are unique values in their own right. They may serialize as a string: the name of the represented value.
|
|
||||||
|
|
||||||
With [Juniper] a [GraphQL enum][0] may be defined by using the [`#[derive(GraphQLEnum)]`][2] attribute on a [Rust enum][3] as long as its variants do not have any fields:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLEnum;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLEnum)]
|
|
||||||
enum Episode {
|
|
||||||
NewHope,
|
|
||||||
Empire,
|
|
||||||
Jedi,
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Renaming
|
|
||||||
|
|
||||||
By default, [enum][3] variants are converted from [Rust]'s standard `PascalCase` naming convention into [GraphQL]'s `SCREAMING_SNAKE_CASE` convention:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLEnum;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLEnum)]
|
|
||||||
enum Episode {
|
|
||||||
NewHope, // exposed as `NEW_HOPE` in GraphQL schema
|
|
||||||
Empire, // exposed as `EMPIRE` in GraphQL schema
|
|
||||||
Jedi, // exposed as `JEDI` in GraphQL schema
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
We can override the name by using the `#[graphql(name = "...")]` attribute:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLEnum;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLEnum)]
|
|
||||||
#[graphql(name = "WrongEpisode")] // now exposed as `WrongEpisode` in GraphQL schema
|
|
||||||
enum Episode {
|
|
||||||
#[graphql(name = "LAST_HOPE")]
|
|
||||||
NewHope, // exposed as `LAST_HOPE` in GraphQL schema
|
|
||||||
Empire,
|
|
||||||
Jedi,
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
Or provide a different renaming policy for all the [enum][3] variants:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLEnum;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLEnum)]
|
|
||||||
#[graphql(rename_all = "none")] // disables any renaming
|
|
||||||
enum Episode {
|
|
||||||
NewHope, // exposed as `NewHope` in GraphQL schema
|
|
||||||
Empire, // exposed as `Empire` in GraphQL schema
|
|
||||||
Jedi, // exposed as `Jedi` in GraphQL schema
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **TIP**: Supported policies are: `SCREAMING_SNAKE_CASE`, `camelCase` and `none` (disables any renaming).
|
|
||||||
|
|
||||||
|
|
||||||
### Documentation and deprecation
|
|
||||||
|
|
||||||
Just like when [defining GraphQL objects](objects/index.md#documentation), the [GraphQL enum][0] type and its values could be [documented][4] and [deprecated][5] via `#[graphql(description = "...")]` and `#[graphql(deprecated = "...")]`/[`#[deprecated]`][13] attributes:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLEnum;
|
|
||||||
#
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
#[derive(GraphQLEnum)]
|
|
||||||
#[graphql(description = "An episode of Star Wars")]
|
|
||||||
enum StarWarsEpisode {
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
#[graphql(description = "This description is visible only in GraphQL schema.")]
|
|
||||||
NewHope,
|
|
||||||
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
#[graphql(desc = "Arguably the best one in the trilogy.")]
|
|
||||||
// ^^^^ shortcut for a `description` argument
|
|
||||||
Empire,
|
|
||||||
|
|
||||||
/// This doc comment is visible in both Rust API docs and GraphQL schema
|
|
||||||
/// descriptions.
|
|
||||||
Jedi,
|
|
||||||
|
|
||||||
#[deprecated(note = "Only visible in Rust.")]
|
|
||||||
#[graphql(deprecated = "We don't really talk about this one.")]
|
|
||||||
// ^^^^^^^^^^ takes precedence over Rust's `#[deprecated]` attribute
|
|
||||||
ThePhantomMenace, // has no description in GraphQL schema
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **NOTE**: Only [GraphQL object][6]/[interface][7] fields and [GraphQL enum][0] values can be [deprecated][5].
|
|
||||||
|
|
||||||
|
|
||||||
### Ignoring
|
|
||||||
|
|
||||||
By default, all [enum][3] variants are included in the generated [GraphQL enum][0] type as values. To prevent including a specific variant, annotate it with the `#[graphql(ignore)]` attribute:
|
|
||||||
```rust
|
|
||||||
# #![allow(dead_code)]
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLEnum;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLEnum)]
|
|
||||||
enum Episode<T> {
|
|
||||||
NewHope,
|
|
||||||
Empire,
|
|
||||||
Jedi,
|
|
||||||
#[graphql(ignore)]
|
|
||||||
Legends(T), // cannot be queried from GraphQL
|
|
||||||
#[graphql(skip)]
|
|
||||||
// ^^^^ alternative naming, up to your preference
|
|
||||||
CloneWars(T), // cannot be queried from GraphQL
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **TIP**: See more available features in the API docs of the [`#[derive(GraphQLEnum)]`][2] attribute.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Enums
|
|
||||||
[1]: https://spec.graphql.org/October2021#sec-Scalars
|
|
||||||
[2]: https://docs.rs/juniper/0.16.1/juniper/derive.GraphQLEnum.html
|
|
||||||
[3]: https://doc.rust-lang.org/reference/items/enumerations.html
|
|
||||||
[4]: https://spec.graphql.org/October2021#sec-Descriptions
|
|
||||||
[5]: https://spec.graphql.org/October2021#sec--deprecated
|
|
||||||
[6]: https://spec.graphql.org/October2021#sec-Objects
|
|
||||||
[7]: https://spec.graphql.org/October2021#sec-Interfaces
|
|
||||||
[13]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute
|
|
|
@ -1,28 +0,0 @@
|
||||||
Type system
|
|
||||||
===========
|
|
||||||
|
|
||||||
Most of the work in working with [Juniper] consists of mapping the [GraphQL type system][0] to the [Rust] types our application uses.
|
|
||||||
|
|
||||||
[Juniper] provides some convenient abstractions making this process as painless as possible.
|
|
||||||
|
|
||||||
Find out more in the individual chapters below:
|
|
||||||
- [Objects](objects/index.md)
|
|
||||||
- [Complex fields](objects/complex_fields.md)
|
|
||||||
- [Context](objects/Context.md)
|
|
||||||
- [Error handling](objects/error/index.md)
|
|
||||||
- [Field errors](objects/error/field.md)
|
|
||||||
- [Schema errors](objects/error/schema.md)
|
|
||||||
- [Generics](objects/generics.md)
|
|
||||||
- [Interfaces](interfaces.md)
|
|
||||||
- [Unions](unions.md)
|
|
||||||
- [Enums](enums.md)
|
|
||||||
- [Input objects](input_objects.md)
|
|
||||||
- [Scalars](scalars.md)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Type-System
|
|
|
@ -1,163 +0,0 @@
|
||||||
Input objects
|
|
||||||
=============
|
|
||||||
|
|
||||||
> [Fields][4] may accept [arguments][5] to configure their behavior. These inputs are often [scalars][12] or [enums][10], but they sometimes need to represent more complex values.
|
|
||||||
>
|
|
||||||
> A [GraphQL input object][0] defines a set of input fields; the input fields are either [scalars][12], [enums][10], or other [input objects][0]. This allows [arguments][5] to accept arbitrarily complex structs.
|
|
||||||
|
|
||||||
In [Juniper], defining a [GraphQL input object][0] is quite straightforward and similar to how [trivial GraphQL objects are defined](objects/index.md) - by using the [`#[derive(GraphQLInputObject)]` attribute][2] on a [Rust struct][struct]:
|
|
||||||
```rust
|
|
||||||
# #![allow(unused_variables)]
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_object, GraphQLInputObject, GraphQLObject};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLInputObject)]
|
|
||||||
struct Coordinate {
|
|
||||||
latitude: f64,
|
|
||||||
longitude: f64
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Root;
|
|
||||||
# #[derive(GraphQLObject)] struct User { name: String }
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Root {
|
|
||||||
fn users_at_location(coordinate: Coordinate, radius: f64) -> Vec<User> {
|
|
||||||
// Send coordinate to database
|
|
||||||
// ...
|
|
||||||
# unimplemented!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Renaming
|
|
||||||
|
|
||||||
Just as with [defining GraphQL objects](objects/index.md#renaming), by default [struct] fields are converted from [Rust]'s standard `snake_case` naming convention into [GraphQL]'s `camelCase` convention:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLInputObject;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLInputObject)]
|
|
||||||
struct Person {
|
|
||||||
first_name: String, // exposed as `firstName` in GraphQL schema
|
|
||||||
last_name: String, // exposed as `lastName` in GraphQL schema
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
We can override the name by using the `#[graphql(name = "...")]` attribute:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLInputObject;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLInputObject)]
|
|
||||||
#[graphql(name = "WebPerson")] // now exposed as `WebPerson` in GraphQL schema
|
|
||||||
struct Person {
|
|
||||||
name: String,
|
|
||||||
age: i32,
|
|
||||||
#[graphql(name = "websiteURL")]
|
|
||||||
website_url: Option<String>, // now exposed as `websiteURL` in GraphQL schema
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
Or provide a different renaming policy for all the [struct] fields:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLInputObject;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLInputObject)]
|
|
||||||
#[graphql(rename_all = "none")] // disables any renaming
|
|
||||||
struct Person {
|
|
||||||
name: String,
|
|
||||||
age: i32,
|
|
||||||
website_url: Option<String>, // exposed as `website_url` in GraphQL schema
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **TIP**: Supported policies are: `SCREAMING_SNAKE_CASE`, `camelCase` and `none` (disables any renaming).
|
|
||||||
|
|
||||||
|
|
||||||
### Documentation
|
|
||||||
|
|
||||||
Similarly, [GraphQL descriptions][7] may be provided by either using [Rust doc comments][6] or with the `#[graphql(description = "...")]` attribute:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLInputObject;
|
|
||||||
#
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
#[derive(GraphQLInputObject)]
|
|
||||||
#[graphql(description = "This description is visible only in GraphQL schema.")]
|
|
||||||
struct Person {
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
#[graphql(desc = "This description is visible only in GraphQL schema.")]
|
|
||||||
// ^^^^ shortcut for a `description` argument
|
|
||||||
name: String,
|
|
||||||
|
|
||||||
/// This doc comment is visible in both Rust API docs and GraphQL schema
|
|
||||||
/// descriptions.
|
|
||||||
age: i32,
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **NOTE**: As of [October 2021 GraphQL specification][spec], [GraphQL input object][0]'s fields **cannot be** [deprecated][9].
|
|
||||||
|
|
||||||
|
|
||||||
### Ignoring
|
|
||||||
|
|
||||||
By default, all [struct] fields are included into the generated [GraphQL input object][0] type. To prevent inclusion of a specific field annotate it with the `#[graphql(ignore)]` attribute:
|
|
||||||
> **WARNING**: Ignored fields must either implement `Default` or be annotated with the `#[graphql(default = <expression>)]` argument.
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLInputObject;
|
|
||||||
#
|
|
||||||
enum System {
|
|
||||||
Cartesian,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLInputObject)]
|
|
||||||
struct Point2D {
|
|
||||||
x: f64,
|
|
||||||
y: f64,
|
|
||||||
#[graphql(ignore, default = System::Cartesian)]
|
|
||||||
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
||||||
// This attribute is required, as we need to be able to construct
|
|
||||||
// a `Point2D` value from the `{ x: 0.0, y: 0.0 }` GraphQL input value,
|
|
||||||
// received from client-side.
|
|
||||||
system: System,
|
|
||||||
// `Default::default()` value is used, if no
|
|
||||||
// `#[graphql(default = <expression>)]` is specified.
|
|
||||||
#[graphql(skip)]
|
|
||||||
// ^^^^ alternative naming, up to your preference
|
|
||||||
shift: f64,
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **TIP**: See more available features in the API docs of the [`#[derive(GraphQLInputObject)]`][2] attribute.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
[struct]: https://doc.rust-lang.org/reference/items/structs.html
|
|
||||||
[spec]: https://spec.graphql.org/October2021
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Input-Objects
|
|
||||||
[2]: https://docs.rs/juniper/0.16.1/juniper/derive.GraphQLInputObject.html
|
|
||||||
[4]: https://spec.graphql.org/October2021#sec-Language.Fields
|
|
||||||
[5]: https://spec.graphql.org/October2021#sec-Language.Arguments
|
|
||||||
[6]: https://doc.rust-lang.org/reference/comments.html#doc-comments
|
|
||||||
[7]: https://spec.graphql.org/October2021#sec-Descriptions
|
|
||||||
[9]: https://spec.graphql.org/October2021#sec--deprecated
|
|
||||||
[10]: https://spec.graphql.org/October2021#sec-Enums
|
|
||||||
[12]: https://spec.graphql.org/October2021#sec-Scalars
|
|
|
@ -1,416 +0,0 @@
|
||||||
Interfaces
|
|
||||||
==========
|
|
||||||
|
|
||||||
> [GraphQL interfaces][0] represent a list of named [fields][4] and their [arguments][5]. [GraphQL objects][10] and [interfaces][0] can then implement these [interfaces][0] which requires that the implementing type will define all [fields][4] defined by those [interfaces][0].
|
|
||||||
|
|
||||||
[GraphQL interfaces][0] map well to interfaces known from common object-oriented languages such as Java or C#, but [Rust], unfortunately, has no concept that maps perfectly to them. The nearest analogue of [GraphQL interfaces][0] are [Rust traits][20], but the main difference is that in [GraphQL] an [interface type][0] serves both as an _abstraction_ and a _boxed value (dispatchable to concrete implementers)_, while in [Rust], a [trait][20] is an _abstraction only_, and _to represent such a boxed value a separate type is required_, like a [trait object][21] or an [enum][22] consisting of implementer types, because [Rust trait][20] doesn't represent a type itself, and so, can have no values.
|
|
||||||
|
|
||||||
Another notable difference is that [GraphQL interfaces][0] are more like [structurally-typed][30] contracts: they _only declare a list of [fields][4]_ a [GraphQL] type should already have. [Rust traits][20], on the other hand, are [type classes][31], which don't really care about existing methods, but, rather, _require to provide implementations for required methods_ despite the fact whether the type already has such methods or not. This difference makes the [trait implementation][23] not a good fit for expressing a [GraphQL interface][0] implementation, because _we don't really need to implement any [fields][4]_, the [GraphQL] type implementing a [GraphQL interface][0] has those [fields][4] already. _We only need to check that [fields'][4] signatures match_.
|
|
||||||
|
|
||||||
That's why [Juniper] takes the following approach to represent [GraphQL interfaces][0], which consists of two parts:
|
|
||||||
1. Either a [struct][24], or a [trait][20] (in case [fields][4] have [arguments][5]), which acts only as a blueprint describing the required list of [fields][4], and is not used in runtime at all.
|
|
||||||
2. An auto-generated [enum][22], representing a dispatchable value-type for the [GraphQL interfaces][0], which may be referred and returned by other [fields][4].
|
|
||||||
|
|
||||||
This may be done by using either the [`#[graphql_interface]` attribute][3] or the [`#[derive(GraphQLInterface)]`][2]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_interface, GraphQLInterface, GraphQLObject};
|
|
||||||
#
|
|
||||||
// By default a `CharacterValue` enum is generated by macro to represent
|
|
||||||
// values of this GraphQL interface.
|
|
||||||
#[derive(GraphQLInterface)]
|
|
||||||
#[graphql(for = Human)] // enumerating all implementers is mandatory
|
|
||||||
struct Character {
|
|
||||||
id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Using a trait to describe the required fields is fine too.
|
|
||||||
#[graphql_interface]
|
|
||||||
#[graphql(enum = HasHomeEnum, for = Human)]
|
|
||||||
// ^^^^ the generated value-type enum can be renamed, if required
|
|
||||||
trait HasHome {
|
|
||||||
fn home_planet(&self) -> &str;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
#[graphql(impl = [CharacterValue, HasHomeEnum])]
|
|
||||||
// ^^^^^^^^^^^^^^ ^^^^^^^^^^^
|
|
||||||
// Notice the enum type names, neither the trait name nor the struct name
|
|
||||||
// is used to refer the GraphQL interface.
|
|
||||||
struct Human {
|
|
||||||
id: String, // also resolves `Character.id` field
|
|
||||||
home_planet: String, // also resolves `HasHome.homePlanet` field
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Interfaces implementing other interfaces
|
|
||||||
|
|
||||||
[GraphQL] allows implementing [interfaces][0] on other [interfaces][0] in addition to [objects][10]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_object, GraphQLInterface, ID};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLInterface)]
|
|
||||||
#[graphql(for = [HumanValue, Luke])]
|
|
||||||
struct Node {
|
|
||||||
id: ID,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLInterface)]
|
|
||||||
#[graphql(impl = NodeValue, for = Luke)]
|
|
||||||
struct Human {
|
|
||||||
id: ID,
|
|
||||||
home_planet: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Luke {
|
|
||||||
id: ID,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(impl = [HumanValue, NodeValue])]
|
|
||||||
impl Luke {
|
|
||||||
fn id(&self) -> &ID {
|
|
||||||
&self.id
|
|
||||||
}
|
|
||||||
|
|
||||||
// As `String` and `&str` aren't distinguished by GraphQL spec and
|
|
||||||
// represent the same `!String` GraphQL scalar, we can use them
|
|
||||||
// interchangeably. The same is applied for `Cow<'a, str>`.
|
|
||||||
// ⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
|
|
||||||
fn home_planet() -> &'static str {
|
|
||||||
"Tatooine"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **NOTE**: Every [interface][0] has to specify all other [interfaces][0]/[objects][0] it implements or implemented for. Missing one of `for = ` or `impl = ` attribute arguments is a **compile-time error**.
|
|
||||||
> ```rust,compile_fail
|
|
||||||
> # extern crate juniper;
|
|
||||||
> # use juniper::{GraphQLInterface, GraphQLObject};
|
|
||||||
> #
|
|
||||||
> #[derive(GraphQLObject)]
|
|
||||||
> pub struct ObjA {
|
|
||||||
> id: String,
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> #[derive(GraphQLInterface)]
|
|
||||||
> #[graphql(for = ObjA)]
|
|
||||||
> // ^^^^^^^^^^ the evaluated program panicked at
|
|
||||||
> // 'Failed to implement interface `Character` on `ObjA`: missing interface
|
|
||||||
> // reference in implementer's `impl` attribute.'
|
|
||||||
> struct Character {
|
|
||||||
> id: String,
|
|
||||||
> }
|
|
||||||
> #
|
|
||||||
> # fn main() {}
|
|
||||||
> ```
|
|
||||||
|
|
||||||
|
|
||||||
### Subtyping and additional `null`able arguments
|
|
||||||
|
|
||||||
[GraphQL] allows implementers (both [objects][10] and other [interfaces][0]) to return "subtypes" instead of an original value. Basically, this allows to impose additional bounds on the implementation.
|
|
||||||
|
|
||||||
Valid "subtypes" are:
|
|
||||||
- [interface][0] implementer instead of an [interface][0] itself:
|
|
||||||
- `I implements T` in place of a `T`;
|
|
||||||
- `Vec<I implements T>` in place of a `Vec<T>`.
|
|
||||||
- [non-`null`][6] value in place of a `null`able:
|
|
||||||
- `T` in place of a `Option<T>`;
|
|
||||||
- `Vec<T>` in place of a `Vec<Option<T>>`.
|
|
||||||
|
|
||||||
These rules are recursively applied, so `Vec<Vec<I implements T>>` is a valid "subtype" of a `Option<Vec<Option<Vec<Option<T>>>>>`.
|
|
||||||
|
|
||||||
Also, [GraphQL] allows implementers to add `null`able [field arguments][5], which aren't present on an original interface.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_interface, graphql_object, GraphQLInterface, ID};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLInterface)]
|
|
||||||
#[graphql(for = [HumanValue, Luke])]
|
|
||||||
struct Node {
|
|
||||||
id: ID,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLInterface)]
|
|
||||||
#[graphql(for = HumanConnectionValue)]
|
|
||||||
struct Connection {
|
|
||||||
nodes: Vec<NodeValue>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLInterface)]
|
|
||||||
#[graphql(impl = NodeValue, for = Luke)]
|
|
||||||
struct Human {
|
|
||||||
id: ID,
|
|
||||||
home_planet: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLInterface)]
|
|
||||||
#[graphql(impl = ConnectionValue)]
|
|
||||||
struct HumanConnection {
|
|
||||||
nodes: Vec<HumanValue>,
|
|
||||||
// ^^^^^^^^^^ notice not `NodeValue`
|
|
||||||
// This can happen, because every `Human` is a `Node` too, so we just
|
|
||||||
// impose additional bounds, which still can be resolved with
|
|
||||||
// `... on Connection { nodes }` syntax.
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Luke {
|
|
||||||
id: ID,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(impl = [HumanValue, NodeValue])]
|
|
||||||
impl Luke {
|
|
||||||
fn id(&self) -> &ID {
|
|
||||||
&self.id
|
|
||||||
}
|
|
||||||
|
|
||||||
fn home_planet(language: Option<String>) -> &'static str {
|
|
||||||
// ^^^^^^^^^^^^^^
|
|
||||||
// Notice additional `null`able field argument, which is missing on
|
|
||||||
// `Human`. Resolving `...on Human { homePlanet }` will provide `None`
|
|
||||||
// for this argument (default argument value).
|
|
||||||
match language.as_deref() {
|
|
||||||
None | Some("en") => "Tatooine",
|
|
||||||
Some("ko") => "타투인",
|
|
||||||
_ => unimplemented!(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **NOTE**: Violating [GraphQL] "subtyping" or additional `null`able [argument][5] rules is a **compile-time error**.
|
|
||||||
>
|
|
||||||
> ```rust,compile_fail
|
|
||||||
> # extern crate juniper;
|
|
||||||
> # use juniper::{graphql_object, GraphQLInterface};
|
|
||||||
> #
|
|
||||||
> pub struct ObjA {
|
|
||||||
> id: String,
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> #[graphql_object]
|
|
||||||
> #[graphql(impl = CharacterValue)]
|
|
||||||
> impl ObjA {
|
|
||||||
> fn id(&self, is_present: bool) -> &str {
|
|
||||||
> // ^^ the evaluated program panicked at
|
|
||||||
> // 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument
|
|
||||||
> // `isPresent` of type `Boolean!` isn't present on the interface and so has
|
|
||||||
> // to be nullable.'
|
|
||||||
> is_present.then_some(&self.id).unwrap_or("missing")
|
|
||||||
> }
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> #[derive(GraphQLInterface)]
|
|
||||||
> #[graphql(for = ObjA)]
|
|
||||||
> struct Character {
|
|
||||||
> id: String,
|
|
||||||
> }
|
|
||||||
> #
|
|
||||||
> # fn main() {}
|
|
||||||
> ```
|
|
||||||
>
|
|
||||||
> ```rust,compile_fail
|
|
||||||
> # extern crate juniper;
|
|
||||||
> # use juniper::{GraphQLInterface, GraphQLObject};
|
|
||||||
> #
|
|
||||||
> #[derive(GraphQLObject)]
|
|
||||||
> #[graphql(impl = CharacterValue)]
|
|
||||||
> pub struct ObjA {
|
|
||||||
> id: Vec<String>,
|
|
||||||
> // ^^ the evaluated program panicked at
|
|
||||||
> // 'Failed to implement interface `Character` on `ObjA`: Field `id`:
|
|
||||||
> // implementer is expected to return a subtype of interface's return
|
|
||||||
> // object: `[String!]!` is not a subtype of `String!`.'
|
|
||||||
> }
|
|
||||||
>
|
|
||||||
> #[derive(GraphQLInterface)]
|
|
||||||
> #[graphql(for = ObjA)]
|
|
||||||
> struct Character {
|
|
||||||
> id: String,
|
|
||||||
> }
|
|
||||||
> #
|
|
||||||
> # fn main() {}
|
|
||||||
> ```
|
|
||||||
|
|
||||||
|
|
||||||
### Default arguments
|
|
||||||
|
|
||||||
[Similarly to GraphQL object fields](objects/complex_fields.md#default-arguments), [GraphQL arguments][4] of [interfaces][0] are able to have default values, though [Rust] doesn't have such notion:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::graphql_interface;
|
|
||||||
#
|
|
||||||
#[graphql_interface]
|
|
||||||
trait Person {
|
|
||||||
fn field1(
|
|
||||||
// Default value can be any valid Rust expression, including a function
|
|
||||||
// call, etc.
|
|
||||||
#[graphql(default = true)]
|
|
||||||
arg1: bool,
|
|
||||||
// If default expression is not specified, then the `Default::default()`
|
|
||||||
// value is used.
|
|
||||||
#[graphql(default)]
|
|
||||||
arg2: i32,
|
|
||||||
) -> String;
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Renaming
|
|
||||||
|
|
||||||
Just as with [defining GraphQL objects](objects/index.md#renaming), by default, [fields][4] are converted from [Rust]'s standard `snake_case` naming convention into [GraphQL]'s `camelCase` convention:
|
|
||||||
|
|
||||||
We can override the name by using the `#[graphql(name = "...")]` attribute:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_interface, GraphQLInterface};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLInterface)]
|
|
||||||
#[graphql(name = "CharacterInterface")]
|
|
||||||
struct Character { // exposed as `CharacterInterface` in GraphQL schema
|
|
||||||
#[graphql(name = "myCustomFieldName")]
|
|
||||||
renamed_field: bool, // exposed as `myCustomFieldName` in GraphQL schema
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_interface]
|
|
||||||
#[graphql(name = "PersonInterface")]
|
|
||||||
trait Person { // exposed as `PersonInterface` in GraphQL schema
|
|
||||||
#[graphql(name = "myCustomFieldName")]
|
|
||||||
fn renamed_field( // exposed as `myCustomFieldName` in GraphQL schema
|
|
||||||
#[graphql(name = "myArgument")]
|
|
||||||
renamed_argument: bool, // exposed as `myArgument` in GraphQL schema
|
|
||||||
) -> bool;
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
Or provide a different renaming policy for all the defined [fields][4]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::graphql_interface;
|
|
||||||
#
|
|
||||||
#[graphql_interface]
|
|
||||||
#[graphql(rename_all = "none")] // disables any renaming
|
|
||||||
trait Person {
|
|
||||||
fn renamed_field( // exposed as `renamed_field` in GraphQL schema
|
|
||||||
renamed_argument: bool, // exposed as `renamed_argument` in GraphQL schema
|
|
||||||
) -> bool;
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **TIP**: Supported policies are: `SCREAMING_SNAKE_CASE`, `camelCase` and `none` (disables any renaming).
|
|
||||||
|
|
||||||
|
|
||||||
### Documentation and deprecation
|
|
||||||
|
|
||||||
Similarly, [GraphQL fields][4] of [interfaces][0] may also be [documented][7] and [deprecated][9] via `#[graphql(description = "...")]` and `#[graphql(deprecated = "...")]`/[`#[deprecated]`][13] attributes:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::graphql_interface;
|
|
||||||
#
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
#[graphql_interface]
|
|
||||||
#[graphql(description = "This description overwrites the one from doc comment.")]
|
|
||||||
trait Person {
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
#[graphql(description = "This description is visible only in GraphQL schema.")]
|
|
||||||
fn empty() -> &'static str;
|
|
||||||
|
|
||||||
#[graphql(desc = "This description is visible only in GraphQL schema.")]
|
|
||||||
// ^^^^ shortcut for a `description` argument
|
|
||||||
fn field(
|
|
||||||
#[graphql(desc = "This description is visible only in GraphQL schema.")]
|
|
||||||
arg: bool,
|
|
||||||
) -> bool;
|
|
||||||
|
|
||||||
/// This doc comment is visible in both Rust API docs and GraphQL schema
|
|
||||||
/// descriptions.
|
|
||||||
#[graphql(deprecated = "Just because.")]
|
|
||||||
fn deprecated_graphql() -> bool;
|
|
||||||
|
|
||||||
// Standard Rust's `#[deprecated]` attribute works too!
|
|
||||||
#[deprecated(note = "Reason is optional, btw!")]
|
|
||||||
fn deprecated_standard() -> bool; // has no description in GraphQL schema
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **NOTE**: Only [GraphQL interface][0]/[object][10] fields and [GraphQL enum][11] values can be [deprecated][9].
|
|
||||||
|
|
||||||
|
|
||||||
### Ignoring
|
|
||||||
|
|
||||||
By default, all [struct][24] fields or [trait][20] methods are considered as [GraphQL fields][4]. If a helper method is needed, or it should be ignored for some reason, then it should be marked with the `#[graphql(ignore)]` attribute:
|
|
||||||
```rust
|
|
||||||
# #![allow(dead_code)]
|
|
||||||
# extern crate juniper;
|
|
||||||
# use std::marker::PhantomPinned;
|
|
||||||
# use juniper::{graphql_interface, GraphQLInterface};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLInterface)]
|
|
||||||
struct Character {
|
|
||||||
id: i32,
|
|
||||||
#[graphql(ignore)]
|
|
||||||
_pin: PhantomPinned,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_interface]
|
|
||||||
trait Person {
|
|
||||||
fn name(&self) -> &str;
|
|
||||||
|
|
||||||
fn age(&self) -> i32;
|
|
||||||
|
|
||||||
#[graphql(ignore)]
|
|
||||||
fn hidden_from_graphql(&self) {
|
|
||||||
// Ignored methods are allowed to have a default implementation!
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql(skip)]
|
|
||||||
// ^^^^ alternative naming, up to your preference
|
|
||||||
fn also_hidden_from_graphql(&self);
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **TIP**: See more available features in the API docs of the [`#[graphql_interface]`][3] attribute.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Interfaces
|
|
||||||
[2]: https://docs.rs/juniper/0.16.1/juniper/derive.GraphQLInterface.html
|
|
||||||
[3]: https://docs.rs/juniper/0.16.1/juniper/attr.graphql_interface.html
|
|
||||||
[4]: https://spec.graphql.org/October2021#sec-Language.Fields
|
|
||||||
[5]: https://spec.graphql.org/October2021#sec-Language.Arguments
|
|
||||||
[6]: https://spec.graphql.org/October2021#sec-Non-Null
|
|
||||||
[7]: https://spec.graphql.org/October2021#sec-Descriptions
|
|
||||||
[9]: https://spec.graphql.org/October2021#sec--deprecated
|
|
||||||
[10]: https://spec.graphql.org/October2021#sec-Objects
|
|
||||||
[11]: https://spec.graphql.org/October2021#sec-Enums
|
|
||||||
[13]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute
|
|
||||||
[20]: https://doc.rust-lang.org/reference/items/traits.html#traits
|
|
||||||
[21]: https://doc.rust-lang.org/reference/types/trait-object.html#trait-objects
|
|
||||||
[22]: https://doc.rust-lang.org/reference/items/enumerations.html#enumerations
|
|
||||||
[23]: https://doc.rust-lang.org/reference/items/implementations.html#trait-implementations
|
|
||||||
[24]: https://doc.rust-lang.org/reference/items/structs.html
|
|
||||||
[30]: https://en.wikipedia.org/wiki/Structural_type_system
|
|
||||||
[31]: https://en.wikipedia.org/wiki/Type_class
|
|
|
@ -1,229 +0,0 @@
|
||||||
Complex fields
|
|
||||||
==============
|
|
||||||
|
|
||||||
Using a plain [Rust struct][struct] for representing a [GraphQL object][0] is easy and trivial but does not cover every case. What if we need to express something non-trivial as a [GraphQL field][4], such as:
|
|
||||||
- Calling non-trivial logic while [executing][1] the [field][4] (like querying database, etc.).
|
|
||||||
- Accepting [field arguments][5].
|
|
||||||
- Defining a circular [GraphQL object][0], where one of its [fields][4] returns the type itself.
|
|
||||||
- Using some other (non-[struct]) [Rust] type to represent a [GraphQL object][0].
|
|
||||||
|
|
||||||
To support these more complicated use cases, we need a way to define a [GraphQL field][4] as a function. In [Juniper] this is achievable by placing the [`#[graphql_object]` attribute][3] on an [`impl` block][6], which turns its methods into [GraphQL fields][4]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_object, GraphQLObject};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Person {
|
|
||||||
name: String,
|
|
||||||
age: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct House {
|
|
||||||
inhabitants: Vec<Person>,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Defines the `House` GraphQL object.
|
|
||||||
#[graphql_object]
|
|
||||||
impl House {
|
|
||||||
// Creates the field `inhabitantWithName(name: String!)`,
|
|
||||||
// returning a `null`able `Person`.
|
|
||||||
fn inhabitant_with_name(&self, name: String) -> Option<&Person> {
|
|
||||||
self.inhabitants.iter().find(|p| p.name == name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **NOTE**: To access global data such as database connections or authentication information, a _context_ is used. To learn more about this, see the ["Context" chapter](context.md).
|
|
||||||
|
|
||||||
|
|
||||||
### Default arguments
|
|
||||||
|
|
||||||
Though [Rust] doesn't have the notion of default arguments, [GraphQL arguments][4] are able to have default values. These default values are used when a GraphQL operation doesn't specify the argument explicitly. In [Juniper], defining a default value for a [GraphQL argument][4] is enabled by the `#[graphql(default)]` attribute:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::graphql_object;
|
|
||||||
#
|
|
||||||
struct Person;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Person {
|
|
||||||
fn field1(
|
|
||||||
// Default value can be any valid Rust expression, including a function
|
|
||||||
// call, etc.
|
|
||||||
#[graphql(default = true)]
|
|
||||||
arg1: bool,
|
|
||||||
// If default expression is not specified, then the `Default::default()`
|
|
||||||
// value is used.
|
|
||||||
#[graphql(default)]
|
|
||||||
arg2: i32,
|
|
||||||
) -> String {
|
|
||||||
format!("{arg1} {arg2}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Renaming
|
|
||||||
|
|
||||||
Like with the [`#[derive(GraphQLObject)]` attribute on structs](index.md#renaming), [field][4] names are converted from [Rust]'s standard `snake_case` naming convention into [GraphQL]'s `camelCase` convention.
|
|
||||||
|
|
||||||
We can override the name by using the `#[graphql(name = "...")]` attribute:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::graphql_object;
|
|
||||||
#
|
|
||||||
struct Person;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(name = "PersonObject")]
|
|
||||||
impl Person { // exposed as `PersonObject` in GraphQL schema
|
|
||||||
#[graphql(name = "myCustomFieldName")]
|
|
||||||
fn renamed_field( // exposed as `myCustomFieldName` in GraphQL schema
|
|
||||||
#[graphql(name = "myArgument")]
|
|
||||||
renamed_argument: bool, // exposed as `myArgument` in GraphQL schema
|
|
||||||
) -> bool {
|
|
||||||
renamed_argument
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
Or provide a different renaming policy for all the defined [fields][4]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::graphql_object;
|
|
||||||
#
|
|
||||||
struct Person;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(rename_all = "none")] // disables any renaming
|
|
||||||
impl Person {
|
|
||||||
fn renamed_field( // exposed as `renamed_field` in GraphQL schema
|
|
||||||
renamed_argument: bool, // exposed as `renamed_argument` in GraphQL schema
|
|
||||||
) -> bool {
|
|
||||||
renamed_argument
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **TIP**: Supported policies are: `SCREAMING_SNAKE_CASE`, `camelCase` and `none` (disables any renaming).
|
|
||||||
|
|
||||||
|
|
||||||
### Documentation and deprecation
|
|
||||||
|
|
||||||
Similarly, [GraphQL fields][4] may also be [documented][7] and [deprecated][9] via `#[graphql(description = "...")]` and `#[graphql(deprecated = "...")]`/[`#[deprecated]`][13] attributes:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::graphql_object;
|
|
||||||
#
|
|
||||||
struct Person;
|
|
||||||
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(description = "This description overwrites the one from doc comment.")]
|
|
||||||
impl Person {
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
#[graphql(description = "This description is visible only in GraphQL schema.")]
|
|
||||||
fn empty() -> &'static str {
|
|
||||||
""
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql(desc = "This description is visible only in GraphQL schema.")]
|
|
||||||
// ^^^^ shortcut for a `description` argument
|
|
||||||
fn field(
|
|
||||||
#[graphql(desc = "This description is visible only in GraphQL schema.")]
|
|
||||||
arg: bool,
|
|
||||||
) -> bool {
|
|
||||||
arg
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This doc comment is visible in both Rust API docs and GraphQL schema
|
|
||||||
/// descriptions.
|
|
||||||
#[graphql(deprecated = "Just because.")]
|
|
||||||
fn deprecated_graphql() -> bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Standard Rust's `#[deprecated]` attribute works too!
|
|
||||||
#[deprecated(note = "Reason is optional, btw!")]
|
|
||||||
fn deprecated_standard() -> bool { // has no description in GraphQL schema
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **NOTE**: Only [GraphQL object][0]/[interface][11] fields and [GraphQL enum][10] values can be [deprecated][9].
|
|
||||||
|
|
||||||
|
|
||||||
### Ignoring
|
|
||||||
|
|
||||||
By default, all methods of an [`impl` block][6] are exposed as [GraphQL fields][4]. If a method should not be exposed as a [GraphQL field][4], it should be defined in a separate [`impl` block][6] or marked with the `#[graphql(ignore)]` attribute:
|
|
||||||
```rust
|
|
||||||
# #![allow(dead_code)]
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::graphql_object;
|
|
||||||
#
|
|
||||||
struct Person {
|
|
||||||
name: String,
|
|
||||||
age: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Person {
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
self.name.as_str()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn age(&self) -> i32 {
|
|
||||||
self.age
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql(ignore)]
|
|
||||||
pub fn hidden_from_graphql(&self) {
|
|
||||||
// whatever goes...
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql(skip)]
|
|
||||||
// ^^^^ alternative naming, up to your preference
|
|
||||||
pub fn also_hidden_from_graphql(&self) {
|
|
||||||
// whatever goes...
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Person {
|
|
||||||
pub fn not_even_considered_for_graphql(&self) {
|
|
||||||
// whatever goes...
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **TIP**: See more available features in the API docs of the [`#[graphql_object]`][3] attribute.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
[struct]: https://doc.rust-lang.org/reference/items/structs.html
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Objects
|
|
||||||
[1]: https://spec.graphql.org/October2021#sec-Execution
|
|
||||||
[2]: https://docs.rs/juniper/0.16.1/juniper/derive.GraphQLObject.html
|
|
||||||
[3]: https://docs.rs/juniper/0.16.1/juniper/attr.graphql_object.html
|
|
||||||
[4]: https://spec.graphql.org/October2021#sec-Language.Fields
|
|
||||||
[5]: https://spec.graphql.org/October2021#sec-Language.Arguments
|
|
||||||
[6]: https://doc.rust-lang.org/reference/items/implementations.html#inherent-implementations
|
|
||||||
[7]: https://spec.graphql.org/October2021#sec-Descriptions
|
|
||||||
[9]: https://spec.graphql.org/October2021#sec--deprecated
|
|
||||||
[10]: https://spec.graphql.org/October2021#sec-Enums
|
|
||||||
[11]: https://spec.graphql.org/October2021#sec-Interfaces
|
|
||||||
[13]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute
|
|
|
@ -1,156 +0,0 @@
|
||||||
Context
|
|
||||||
=======
|
|
||||||
|
|
||||||
_Context_ is a feature in [Juniper] that lets [field][4] resolvers access global data, most commonly database connections or authentication information.
|
|
||||||
|
|
||||||
Let's say that we have a simple `User`s database in a `HashMap`:
|
|
||||||
```rust
|
|
||||||
# #![allow(dead_code)]
|
|
||||||
# use std::collections::HashMap;
|
|
||||||
#
|
|
||||||
struct Database {
|
|
||||||
users: HashMap<i32, User>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct User {
|
|
||||||
id: i32,
|
|
||||||
name: String,
|
|
||||||
friend_ids: Vec<i32>,
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
We would like to define a `friends` [field][4] on `User` that returns a list of `User` [objects][0]. In order to write such a [field][4] we need to query a `Database`. To accomplish this we must first mark the `Database` as a valid context type and then assign it to the `User` [object][0]. To gain access to the context in the `friends` [field][4], we need to specify an argument with the same type as the specified context:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use std::collections::HashMap;
|
|
||||||
# use juniper::graphql_object;
|
|
||||||
#
|
|
||||||
struct Database {
|
|
||||||
users: HashMap<i32, User>,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mark the `Database` as a valid context type for Juniper.
|
|
||||||
impl juniper::Context for Database {}
|
|
||||||
|
|
||||||
struct User {
|
|
||||||
id: i32,
|
|
||||||
name: String,
|
|
||||||
friend_ids: Vec<i32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(context = Database)] // assign `Database` as the context type
|
|
||||||
impl User {
|
|
||||||
// Inject the `Database` context by specifying an argument with the
|
|
||||||
// context type:
|
|
||||||
// - the type must be a reference;
|
|
||||||
// - the name of the argument SHOULD be `context` (or `ctx`).
|
|
||||||
fn friends<'db>(&self, context: &'db Database) -> Vec<&'db User> {
|
|
||||||
// ^^^^^^^ or `ctx`, up to your preference
|
|
||||||
self.friend_ids.iter()
|
|
||||||
.map(|id| {
|
|
||||||
context.users.get(&id).expect("could not find `User` with ID")
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn friend<'db>(
|
|
||||||
&self,
|
|
||||||
id: i32,
|
|
||||||
// Alternatively, the context argument may be marked with an attribute,
|
|
||||||
// and thus, named arbitrary.
|
|
||||||
#[graphql(context)] db: &'db Database,
|
|
||||||
// ^^^^^^^ or `ctx`, up to your preference
|
|
||||||
) -> Option<&'db User> {
|
|
||||||
self.friend_ids.contains(&id).then(|| {
|
|
||||||
db.users.get(&id).expect("could not find `User` with ID")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
self.name.as_str()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn id(&self) -> i32 {
|
|
||||||
self.id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Mutating and mutable references
|
|
||||||
|
|
||||||
Context cannot be a mutable reference as [fields][4] may be resolved concurrently. If something in the context requires a mutable reference, the context type should leverage the [_interior mutability_ pattern][5] (e.g. use `RwLock`, `RefCell` or similar).
|
|
||||||
|
|
||||||
For example, when using async runtime with [work stealing][6] (like [`tokio`]), which obviously requires thread safety in addition, we will need to use a corresponding async version of `RwLock`:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# extern crate tokio;
|
|
||||||
# use std::collections::HashMap;
|
|
||||||
# use juniper::graphql_object;
|
|
||||||
use tokio::sync::RwLock;
|
|
||||||
|
|
||||||
struct Database {
|
|
||||||
requested_count: HashMap<i32, i32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Since we cannot directly implement `juniper::Context`
|
|
||||||
// for `RwLock`, we use the newtype idiom.
|
|
||||||
struct DatabaseContext(RwLock<Database>);
|
|
||||||
|
|
||||||
impl juniper::Context for DatabaseContext {}
|
|
||||||
|
|
||||||
struct User {
|
|
||||||
id: i32,
|
|
||||||
name: String
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(context = DatabaseContext)]
|
|
||||||
impl User {
|
|
||||||
async fn times_requested<'db>(&self, ctx: &'db DatabaseContext) -> i32 {
|
|
||||||
// Acquire a mutable reference and `.await` if async `RwLock` is used,
|
|
||||||
// which is necessary if context consists of async operations like
|
|
||||||
// querying remote databases.
|
|
||||||
|
|
||||||
// Obtain base type.
|
|
||||||
let DatabaseContext(db) = ctx;
|
|
||||||
// If context is immutable use `.read()` on `RwLock` instead.
|
|
||||||
let mut db = db.write().await;
|
|
||||||
|
|
||||||
// Perform a mutable operation.
|
|
||||||
db.requested_count
|
|
||||||
.entry(self.id)
|
|
||||||
.and_modify(|e| *e += 1)
|
|
||||||
.or_insert(1)
|
|
||||||
.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
self.name.as_str()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn id(&self) -> i32 {
|
|
||||||
self.id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **TIP**: Replace `tokio::sync::RwLock` with `std::sync::RwLock` (or similar) if you don't intend to use async resolving.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[`tokio`]: https://docs.rs/tokio
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Objects
|
|
||||||
[4]: https://spec.graphql.org/October2021#sec-Language.Fields
|
|
||||||
[5]: https://doc.rust-lang.org/reference/interior-mutability.html#interior-mutability
|
|
||||||
[6]: https://en.wikipedia.org/wiki/Work_stealing
|
|
|
@ -1,183 +0,0 @@
|
||||||
Field errors
|
|
||||||
============
|
|
||||||
|
|
||||||
[Rust] provides [two ways of dealing with errors][11]:
|
|
||||||
- [`Result<T, E>`][12] for recoverable errors;
|
|
||||||
- [`panic!`][13] for unrecoverable errors.
|
|
||||||
|
|
||||||
[Juniper] does not do anything about panicking, it naturally bubbles up to the surrounding code/framework and can be dealt with there.
|
|
||||||
|
|
||||||
For recoverable errors, [Juniper] works well with the [built-in `Result` type][12]. You can use the [`?` operator][14] and things will work as you expect them to:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use std::{fs::File, io::Read, path::PathBuf, str};
|
|
||||||
# use juniper::{graphql_object, FieldResult};
|
|
||||||
#
|
|
||||||
struct Example {
|
|
||||||
filename: PathBuf,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Example {
|
|
||||||
fn contents(&self) -> FieldResult<String> {
|
|
||||||
let mut file = File::open(&self.filename)?;
|
|
||||||
let mut contents = String::new();
|
|
||||||
file.read_to_string(&mut contents)?;
|
|
||||||
Ok(contents)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn foo() -> FieldResult<Option<String>> {
|
|
||||||
// Some invalid bytes.
|
|
||||||
let invalid = vec![128, 223];
|
|
||||||
|
|
||||||
Ok(Some(str::from_utf8(&invalid)?.to_string()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
[`FieldResult<T>`][21] is an alias for [`Result<T, FieldError>`][22], which is the [error type][1] all fallible [fields][6] must return. By using the [`?` operator][14], any type that implements the [`Display` trait][15] (which most of the error types out there do) can be automatically converted into a [`FieldError`][22].
|
|
||||||
|
|
||||||
> **TIP**: If a custom conversion into a [`FieldError`][22] is needed (to [fill up `extensions`][2], for example), the [`IntoFieldError` trait][23] should be implemented.
|
|
||||||
|
|
||||||
> **NOTE**: [`FieldError`][22]s are [GraphQL field errors][1] and are [not visible][9] in a [GraphQL schema][8] in any way.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Error payloads, `null`, and partial errors
|
|
||||||
|
|
||||||
[Juniper]'s error behavior conforms to the [GraphQL specification][0].
|
|
||||||
|
|
||||||
When a [field][6] returns an [error][11], the [field][6]'s result is replaced by `null`, and an additional `errors` object is created at the top level of the [response][7], and the [execution][5] is resumed.
|
|
||||||
|
|
||||||
Let's run the following query against the previous example:
|
|
||||||
```graphql
|
|
||||||
{
|
|
||||||
example {
|
|
||||||
contents
|
|
||||||
foo
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
If `str::from_utf8` results in a `std::str::Utf8Error`, then the following will be returned:
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"example": {
|
|
||||||
"contents": "<Contents of the file>",
|
|
||||||
"foo": null
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"errors": [{
|
|
||||||
"message": "invalid utf-8 sequence of 2 bytes from index 0",
|
|
||||||
"locations": [{"line": 2, "column": 4}]
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
> Since [`Non-Null` type][4] [fields][5] cannot be **null**, [field errors][1] are propagated to be handled by the parent [field][5]. If the parent [field][5] may be **null** then it resolves to **null**, otherwise if it is a [`Non-Null` type][4], the [field error][1] is further propagated to its parent [field][5].
|
|
||||||
|
|
||||||
For example, with the following query:
|
|
||||||
```graphql
|
|
||||||
{
|
|
||||||
example {
|
|
||||||
contents
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
If the `File::open()` above results in a `std::io::ErrorKind::PermissionDenied`, the following ill be returned:
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"data": null,
|
|
||||||
"errors": [{
|
|
||||||
"message": "Permission denied (os error 13)",
|
|
||||||
"locations": [{"line": 2, "column": 4}]
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Additional information
|
|
||||||
|
|
||||||
Sometimes it's desirable to return additional structured error information to clients. This can be accomplished by implementing the [`IntoFieldError` trait][23]:
|
|
||||||
```rust
|
|
||||||
# #[macro_use] extern crate juniper;
|
|
||||||
# use juniper::{graphql_object, FieldError, IntoFieldError, ScalarValue};
|
|
||||||
#
|
|
||||||
enum CustomError {
|
|
||||||
WhateverNotSet,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<S: ScalarValue> IntoFieldError<S> for CustomError {
|
|
||||||
fn into_field_error(self) -> FieldError<S> {
|
|
||||||
match self {
|
|
||||||
Self::WhateverNotSet => FieldError::new(
|
|
||||||
"Whatever does not exist",
|
|
||||||
graphql_value!({
|
|
||||||
"type": "NO_WHATEVER"
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Example {
|
|
||||||
whatever: Option<bool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Example {
|
|
||||||
fn whatever(&self) -> Result<bool, CustomError> {
|
|
||||||
if let Some(value) = self.whatever {
|
|
||||||
return Ok(value);
|
|
||||||
}
|
|
||||||
Err(CustomError::WhateverNotSet)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
And the specified structured error information will be included into the [error's `extensions`][2]:
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"errors": [{
|
|
||||||
"message": "Whatever does not exist",
|
|
||||||
"locations": [{"line": 2, "column": 4}],
|
|
||||||
"extensions": {
|
|
||||||
"type": "NO_WHATEVER"
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
> **NOTE**: This pattern is particularly useful when it comes to instrumentation of returned [field errors][1] with custom error codes or additional diagnostics (like stack traces or tracing IDs).
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Handling-Field-Errors
|
|
||||||
[1]: https://spec.graphql.org/October2021#sec-Errors.Field-errors
|
|
||||||
[2]: https://spec.graphql.org/October2021#sel-GAPHRPZCAACCC_7Q
|
|
||||||
[4]: https://spec.graphql.org/October2021#sec-Non-Null
|
|
||||||
[5]: https://spec.graphql.org/October2021#sec-Execution
|
|
||||||
[6]: https://spec.graphql.org/October2021#sec-Language.Fields
|
|
||||||
[7]: https://spec.graphql.org/October2021#sec-Response
|
|
||||||
[8]: https://graphql.org/learn/schema
|
|
||||||
[9]: https://spec.graphql.org/October2021#sec-Introspection
|
|
||||||
[11]: https://doc.rust-lang.org/book/ch09-00-error-handling.html
|
|
||||||
[12]: https://doc.rust-lang.org/stable/std/result/enum.Result.html
|
|
||||||
[13]: https://doc.rust-lang.org/stable/std/macro.panic.html
|
|
||||||
[14]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator
|
|
||||||
[15]: https://doc.rust-lang.org/stable/std/fmt/trait.Display.html
|
|
||||||
[21]: https://docs.rs/juniper/0.16.1/juniper/executor/type.FieldResult.html
|
|
||||||
[22]: https://docs.rs/juniper/0.16.1/juniper/executor/struct.FieldError.html
|
|
||||||
[23]: https://docs.rs/juniper/0.16.1/juniper/executor/trait.IntoFieldError.html
|
|
|
@ -1,26 +0,0 @@
|
||||||
Error handling
|
|
||||||
==============
|
|
||||||
|
|
||||||
Error handling in [GraphQL] can be done in multiple ways. We will cover the two different error handling models mostly used:
|
|
||||||
1. [Implicit field results](field.md).
|
|
||||||
2. [Explicit errors backend by GraphQL schema](schema.md).
|
|
||||||
|
|
||||||
Choosing the right error handling method depends on the requirements of the application and the concrete error happening. Investigating both approaches is beneficial.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Comparison
|
|
||||||
|
|
||||||
The [first approach](field.md) (where every error is a [field error][1]) is easier to implement. However, clients won't know what errors may occur and instead will have to infer what happens from the [error message][2]. This is brittle and could change over time due to either clients or server changing. Therefore, extensive integration testing between clients and server is required to maintain the implicit contract between the two.
|
|
||||||
|
|
||||||
[Encoding non-critical errors in a GraphQL schema](schema.md) makes the contract between clients and the server explicit. This allows clients to understand and handle these errors correctly and the server to know when changes are potentially breaking clients. However, encoding this error information into a [GraphQL schema][8] requires additional code and up-front definition of non-critical errors.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
|
|
||||||
[1]: https://spec.graphql.org/October2021#sec-Errors.Field-errors
|
|
||||||
[2]: https://spec.graphql.org/October2021/#sel-GAPHRPDCAACCyD57Z
|
|
||||||
[8]: https://graphql.org/learn/schema
|
|
|
@ -1,336 +0,0 @@
|
||||||
Schema errors
|
|
||||||
=============
|
|
||||||
|
|
||||||
[Rust]'s model of errors can be adapted for [GraphQL]. [Rust]'s panic is similar to a [field error][1] - the whole query is aborted and nothing can be extracted (except for error related information).
|
|
||||||
|
|
||||||
Not all errors require this strict handling. Recoverable or partial errors can be put into a [GraphQL schema][8], so the client can intelligently handle them.
|
|
||||||
|
|
||||||
To implement this approach, all errors must be partitioned into two classes:
|
|
||||||
- _Critical_ errors that cannot be fixed by clients (e.g. a database error).
|
|
||||||
- _Recoverable_ errors that can be fixed by clients (e.g. invalid input data).
|
|
||||||
|
|
||||||
Critical errors are returned from resolvers as [field errors][1] (from the [previous chapter](field.md)). Recoverable errors are part of a [GraphQL schema][8] and can be handled gracefully by clients. Similar to [Rust], [GraphQL] allows similar error models with [unions][9] (see ["Unions" chapter](../../unions.md)).
|
|
||||||
|
|
||||||
|
|
||||||
### Example: Simple
|
|
||||||
|
|
||||||
In this example, basic input validation is implemented with [GraphQL types][7]. [Strings][5] are used to identify the problematic [field][6] name. Errors for a particular [field][6] are also returned as a [string][5].
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_object, GraphQLObject, GraphQLUnion};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
pub struct Item {
|
|
||||||
name: String,
|
|
||||||
quantity: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
pub struct ValidationError {
|
|
||||||
field: String,
|
|
||||||
message: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
pub struct ValidationErrors {
|
|
||||||
errors: Vec<ValidationError>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLUnion)]
|
|
||||||
pub enum GraphQLResult {
|
|
||||||
Ok(Item),
|
|
||||||
Err(ValidationErrors),
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Mutation;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Mutation {
|
|
||||||
fn add_item(&self, name: String, quantity: i32) -> GraphQLResult {
|
|
||||||
let mut errors = Vec::new();
|
|
||||||
|
|
||||||
if !(10 <= name.len() && name.len() <= 100) {
|
|
||||||
errors.push(ValidationError {
|
|
||||||
field: "name".into(),
|
|
||||||
message: "between 10 and 100".into(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if !(1 <= quantity && quantity <= 10) {
|
|
||||||
errors.push(ValidationError {
|
|
||||||
field: "quantity".into(),
|
|
||||||
message: "between 1 and 10".into(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if errors.is_empty() {
|
|
||||||
GraphQLResult::Ok(Item { name, quantity })
|
|
||||||
} else {
|
|
||||||
GraphQLResult::Err(ValidationErrors { errors })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
Each function may have a different return type and depending on the input parameters a new result type may be required. For example, adding a `User` would require a new result type containing the variant `Ok(User)`instead of `Ok(Item)`.
|
|
||||||
|
|
||||||
> **NOTE**: In this example the returned [string][5] contains a server-side localized error message. However, it is also
|
|
||||||
possible to return a unique string identifier and have the client present a localized string to its users.
|
|
||||||
|
|
||||||
The client can send a mutation request and handle the resulting errors in the following manner:
|
|
||||||
```graphql
|
|
||||||
{
|
|
||||||
mutation {
|
|
||||||
addItem(name: "", quantity: 0) {
|
|
||||||
... on Item {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
... on ValidationErrors {
|
|
||||||
errors {
|
|
||||||
field
|
|
||||||
message
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **NOTE**: A useful side effect of this approach is to have partially successful queries or mutations. If one resolver fails, the results of the successful resolvers are not discarded.
|
|
||||||
|
|
||||||
|
|
||||||
### Example: Complex
|
|
||||||
|
|
||||||
Instead of using [strings][5] to propagate errors, it is possible to use [GraphQL type system][7] to describe the errors more precisely.
|
|
||||||
|
|
||||||
For each fallible [input argument][4] we create a [field][6] in a [GraphQL object][10]. The [field][6] is set if the validation for that particular [argument][4] fails.
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_object, GraphQLObject, GraphQLUnion};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
pub struct Item {
|
|
||||||
name: String,
|
|
||||||
quantity: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
pub struct ValidationError {
|
|
||||||
name: Option<String>,
|
|
||||||
quantity: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLUnion)]
|
|
||||||
pub enum GraphQLResult {
|
|
||||||
Ok(Item),
|
|
||||||
Err(ValidationError),
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Mutation;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Mutation {
|
|
||||||
fn add_item(&self, name: String, quantity: i32) -> GraphQLResult {
|
|
||||||
let mut error = ValidationError {
|
|
||||||
name: None,
|
|
||||||
quantity: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
if !(10 <= name.len() && name.len() <= 100) {
|
|
||||||
error.name = Some("between 10 and 100".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
if !(1 <= quantity && quantity <= 10) {
|
|
||||||
error.quantity = Some("between 1 and 10".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
if error.name.is_none() && error.quantity.is_none() {
|
|
||||||
GraphQLResult::Ok(Item { name, quantity })
|
|
||||||
} else {
|
|
||||||
GraphQLResult::Err(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **NOTE**: We will likely want some kind of code generation to reduce repetition as the number of types required is significantly larger than before. Each resolver function has a custom `ValidationResult` which contains only [fields][6] provided by the function.
|
|
||||||
|
|
||||||
So, all the expected errors are handled directly inside the query. Additionally, all non-critical errors are known in advance by both the server and the client:
|
|
||||||
```graphql
|
|
||||||
{
|
|
||||||
mutation {
|
|
||||||
addItem {
|
|
||||||
... on Item {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
... on ValidationErrorsItem {
|
|
||||||
name
|
|
||||||
quantity
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Example: Complex with critical errors
|
|
||||||
|
|
||||||
Our examples so far have only included non-critical errors. Providing errors inside a [GraphQL schema][8] still allows us to return unexpected critical errors when they occur.
|
|
||||||
|
|
||||||
In the following example, a theoretical database could fail and would generate errors. Since it is not common for a database to fail, the corresponding error is returned as a [critical error][1]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_object, graphql_value, FieldError, GraphQLObject, GraphQLUnion, ScalarValue};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
pub struct Item {
|
|
||||||
name: String,
|
|
||||||
quantity: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
pub struct ValidationErrorItem {
|
|
||||||
name: Option<String>,
|
|
||||||
quantity: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLUnion)]
|
|
||||||
pub enum GraphQLResult {
|
|
||||||
Ok(Item),
|
|
||||||
Err(ValidationErrorItem),
|
|
||||||
}
|
|
||||||
|
|
||||||
pub enum ApiError {
|
|
||||||
Database,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<S: ScalarValue> juniper::IntoFieldError<S> for ApiError {
|
|
||||||
fn into_field_error(self) -> FieldError<S> {
|
|
||||||
match self {
|
|
||||||
Self::Database => FieldError::new(
|
|
||||||
"Internal database error",
|
|
||||||
graphql_value!({"type": "DATABASE"}),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Mutation;
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl Mutation {
|
|
||||||
fn add_item(&self, name: String, quantity: i32) -> Result<GraphQLResult, ApiError> {
|
|
||||||
let mut error = ValidationErrorItem {
|
|
||||||
name: None,
|
|
||||||
quantity: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
if !(10 <= name.len() && name.len() <= 100) {
|
|
||||||
error.name = Some("between 10 and 100".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
if !(1 <= quantity && quantity <= 10) {
|
|
||||||
error.quantity = Some("between 1 and 10".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
if error.name.is_none() && error.quantity.is_none() {
|
|
||||||
Ok(GraphQLResult::Ok(Item { name, quantity }))
|
|
||||||
} else {
|
|
||||||
Ok(GraphQLResult::Err(error))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Example: Shopify API
|
|
||||||
|
|
||||||
The [Shopify API] implements a similar approach. Their API is a good reference to explore this approach in a real world application.
|
|
||||||
|
|
||||||
|
|
||||||
### Example: Non-struct [objects][10]
|
|
||||||
|
|
||||||
Up until now, we've only looked at mapping [structs][20] to [GraphQL objects][10]. However, any [Rust] type can be exposed a [GraphQL object][10].
|
|
||||||
|
|
||||||
Using `Result`-like [enums][1] can be a useful way of reporting validation errors from a mutation:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_object, GraphQLObject};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct User {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct ValidationError {
|
|
||||||
field: String,
|
|
||||||
message: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
enum SignUpResult {
|
|
||||||
Ok(User),
|
|
||||||
Error(Vec<ValidationError>),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
impl SignUpResult {
|
|
||||||
fn user(&self) -> Option<&User> {
|
|
||||||
match self {
|
|
||||||
Self::Ok(user) => Some(user),
|
|
||||||
Self::Error(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn error(&self) -> Option<&[ValidationError]> {
|
|
||||||
match self {
|
|
||||||
Self::Ok(_) => None,
|
|
||||||
Self::Error(errs) => Some(errs.as_slice())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
Here, we use an [enum][21] to decide whether a client's input data is valid or not, and it could be used as the result of e.g. a `signUp` mutation:
|
|
||||||
```graphql
|
|
||||||
{
|
|
||||||
mutation {
|
|
||||||
signUp(name: "wrong") {
|
|
||||||
user {
|
|
||||||
name
|
|
||||||
}
|
|
||||||
error {
|
|
||||||
field
|
|
||||||
message
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
[Shopify API]: https://shopify.dev/docs/admin-api/graphql/reference
|
|
||||||
|
|
||||||
[1]: https://spec.graphql.org/October2021#sec-Errors.Field-errors
|
|
||||||
[4]: https://spec.graphql.org/October2021#sec-Language.Arguments
|
|
||||||
[5]: https://spec.graphql.org/October2021#sec-String
|
|
||||||
[6]: https://spec.graphql.org/October2021#sec-Language.Fields
|
|
||||||
[7]: https://spec.graphql.org/October2021#sec-Types
|
|
||||||
[8]: https://graphql.org/learn/schema
|
|
||||||
[9]: https://spec.graphql.org/October2021#sec-Unions
|
|
||||||
[10]: https://spec.graphql.org/October2021#sec-Objects
|
|
||||||
[20]: https://doc.rust-lang.org/reference/items/structs.html
|
|
||||||
[21]: https://doc.rust-lang.org/reference/items/enumerations.html
|
|
|
@ -1,78 +0,0 @@
|
||||||
Generics
|
|
||||||
========
|
|
||||||
|
|
||||||
Yet another point where [GraphQL] and [Rust] differs is in how generics work:
|
|
||||||
- In [Rust], almost any type could be generic - that is, take type parameters.
|
|
||||||
- In [GraphQL], there are only two generic types: [lists][1] and [non-`null`ables][2].
|
|
||||||
|
|
||||||
This poses a restriction on what we can expose in [GraphQL] from [Rust]: no generic structs can be exposed - all type parameters must be bound. For example, we cannot expose `Result<T, E>` as a [GraphQL type][0], but we _can_ expose `Result<User, String>` as a [GraphQL type][0].
|
|
||||||
|
|
||||||
Let's make a slightly more compact but generic implementation of [the last schema error example](error/schema.md#example-non-struct-objects):
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_object, GraphQLObject};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct User {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct ForumPost {
|
|
||||||
title: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct ValidationError {
|
|
||||||
field: String,
|
|
||||||
message: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct MutationResult<T>(Result<T, Vec<ValidationError>>);
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(name = "UserResult")]
|
|
||||||
impl MutationResult<User> {
|
|
||||||
fn user(&self) -> Option<&User> {
|
|
||||||
self.0.as_ref().ok()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn error(&self) -> Option<&[ValidationError]> {
|
|
||||||
self.0.as_ref().err().map(Vec::as_slice)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[graphql_object]
|
|
||||||
#[graphql(name = "ForumPostResult")]
|
|
||||||
impl MutationResult<ForumPost> {
|
|
||||||
fn forum_post(&self) -> Option<&ForumPost> {
|
|
||||||
self.0.as_ref().ok()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn error(&self) -> Option<&[ValidationError]> {
|
|
||||||
self.0.as_ref().err().map(Vec::as_slice)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
Here, we've made a wrapper around a `Result` and exposed some concrete instantiations of `Result<T, E>` as distinct [GraphQL objects][3].
|
|
||||||
|
|
||||||
> **NOTE**: The reason we needed the wrapper is of [Rust]'s [orphan rules][10] (both the `Result` and [Juniper]'s internal traits are from third-party sources).
|
|
||||||
|
|
||||||
> **NOTE**: Because we're using generics, we also need to specify a `name` for our instantiated [GraphQL types][0]. Even if [Juniper] _could_ figure out the name, `MutationResult<User>` wouldn't be a [valid GraphQL type name][4]. And, also, two different [GraphQL types][0] cannot have the same `MutationResult` name, inferred by default.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Types
|
|
||||||
[1]: https://spec.graphql.org/October2021#sec-List
|
|
||||||
[2]: https://spec.graphql.org/October2021#sec-Non-Null
|
|
||||||
[3]: https://spec.graphql.org/October2021#sec-Objects
|
|
||||||
[4]: https://spec.graphql.org/October2021#sec-Names
|
|
||||||
[10]: https://doc.rust-lang.org/reference/items/implementations.html#trait-implementation-coherence
|
|
|
@ -1,228 +0,0 @@
|
||||||
Objects
|
|
||||||
=======
|
|
||||||
|
|
||||||
> [GraphQL objects][0] represent a list of named fields, each of which yield a value of a specific type.
|
|
||||||
|
|
||||||
When declaring a [GraphQL schema][schema], most of the time we deal with [GraphQL objects][0], because they are the only place where we actually define the behavior once [schema] gets [executed][1].
|
|
||||||
|
|
||||||
There are two ways to define a [GraphQL object][0] in [Juniper]:
|
|
||||||
1. The easiest way, suitable for trivial cases, is to use the [`#[derive(GraphQLObject)]` attribute][2] on a [struct], as described below.
|
|
||||||
2. The other way, using the [`#[graphql_object]` attribute][3], is described in the ["Complex fields" chapter](complex_fields.md).
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Trivial
|
|
||||||
|
|
||||||
While any type in [Rust] can be exposed as a [GraphQL object][0], the most common one is a [struct]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLObject;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Person {
|
|
||||||
name: String,
|
|
||||||
age: i32,
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
This creates a [GraphQL object][0] type called `Person`, with two fields: `name` of type `String!`, and `age` of type `Int!`. Because of [Rust]'s type system, everything is exported as [non-`null`][4] by default.
|
|
||||||
|
|
||||||
> **TIP**: If a `null`able field is required, the most obvious way is to use `Option`. Or [`Nullable`] for distinguishing between [explicit and implicit `null`s][14].
|
|
||||||
|
|
||||||
|
|
||||||
### Documentation
|
|
||||||
|
|
||||||
We should take advantage of the fact that [GraphQL] is [self-documenting][5] and add descriptions to the defined [GraphQL object][0] type and its fields. [Juniper] will automatically use associated [Rust doc comments][6] as [GraphQL descriptions][7]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLObject;
|
|
||||||
#
|
|
||||||
/// Information about a person.
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Person {
|
|
||||||
/// The person's full name, including both first and last names.
|
|
||||||
name: String,
|
|
||||||
|
|
||||||
/// The person's age in years, rounded down.
|
|
||||||
age: i32,
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
If using [Rust doc comments][6] is not desired (for example, when we want to keep [Rust] API docs and GraphQL schema descriptions different), the `#[graphql(description = "...")]` attribute can be used instead, which takes precedence over [Rust doc comments][6]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLObject;
|
|
||||||
#
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
#[graphql(description = "This description is visible only in GraphQL schema.")]
|
|
||||||
struct Person {
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
#[graphql(desc = "This description is visible only in GraphQL schema.")]
|
|
||||||
// ^^^^ shortcut for a `description` argument
|
|
||||||
name: String,
|
|
||||||
|
|
||||||
/// This doc comment is visible in both Rust API docs and GraphQL schema
|
|
||||||
/// descriptions.
|
|
||||||
age: i32,
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Renaming
|
|
||||||
|
|
||||||
By default, [struct] fields are converted from [Rust]'s standard `snake_case` naming convention into [GraphQL]'s `camelCase` convention:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLObject;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Person {
|
|
||||||
first_name: String, // exposed as `firstName` in GraphQL schema
|
|
||||||
last_name: String, // exposed as `lastName` in GraphQL schema
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
We can override the name by using the `#[graphql(name = "...")]` attribute:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLObject;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
#[graphql(name = "WebPerson")] // now exposed as `WebPerson` in GraphQL schema
|
|
||||||
struct Person {
|
|
||||||
name: String,
|
|
||||||
age: i32,
|
|
||||||
#[graphql(name = "websiteURL")]
|
|
||||||
website_url: Option<String>, // now exposed as `websiteURL` in GraphQL schema
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
Or provide a different renaming policy for all the [struct] fields:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLObject;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
#[graphql(rename_all = "none")] // disables any renaming
|
|
||||||
struct Person {
|
|
||||||
name: String,
|
|
||||||
age: i32,
|
|
||||||
website_url: Option<String>, // exposed as `website_url` in GraphQL schema
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **TIP**: Supported policies are: `SCREAMING_SNAKE_CASE`, `camelCase` and `none` (disables any renaming).
|
|
||||||
|
|
||||||
|
|
||||||
### Deprecation
|
|
||||||
|
|
||||||
To [deprecate][9] a [GraphQL object][0] field, either the `#[graphql(deprecated = "...")]` attribute, or [Rust's `#[deprecated]` attribute][13], should be used:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLObject;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Person {
|
|
||||||
name: String,
|
|
||||||
age: i32,
|
|
||||||
#[graphql(deprecated = "Please use the `name` field instead.")]
|
|
||||||
first_name: String,
|
|
||||||
#[deprecated(note = "Please use the `name` field instead.")]
|
|
||||||
last_name: String,
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **NOTE**: Only [GraphQL object][0]/[interface][11] fields and [GraphQL enum][10] values can be [deprecated][9].
|
|
||||||
|
|
||||||
|
|
||||||
### Ignoring
|
|
||||||
|
|
||||||
By default, all [struct] fields are included into the generated [GraphQL object][0] type. To prevent inclusion of a specific field annotate it with the `#[graphql(ignore)]` attribute:
|
|
||||||
```rust
|
|
||||||
# #![allow(dead_code)]
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLObject;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Person {
|
|
||||||
name: String,
|
|
||||||
age: i32,
|
|
||||||
#[graphql(ignore)]
|
|
||||||
password_hash: String, // cannot be queried from GraphQL
|
|
||||||
#[graphql(skip)]
|
|
||||||
// ^^^^ alternative naming, up to your preference
|
|
||||||
is_banned: bool, // cannot be queried from GraphQL
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **TIP**: See more available features in the API docs of the [`#[derive(GraphQLObject)]`][2] attribute.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Relationships
|
|
||||||
|
|
||||||
[GraphQL object][0] fields can be of any [GraphQL] type, except [input objects][8].
|
|
||||||
|
|
||||||
Let's see what it means to build relationships between [objects][0]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLObject;
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Person {
|
|
||||||
name: String,
|
|
||||||
age: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct House {
|
|
||||||
address: Option<String>, // converted into `String` (`null`able)
|
|
||||||
inhabitants: Vec<Person>, // converted into `[Person!]!`
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
Because `Person` is a valid [GraphQL] type, we can have a `Vec<Person>` in a [struct], and it'll be automatically converted into a [list][12] of [non-`null`able][4] `Person` [objects][0].
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[`Nullable`]: https://docs.rs/juniper/0.16.1/juniper/enum.Nullable.html
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
[schema]: https://graphql.org/learn/schema
|
|
||||||
[struct]: https://doc.rust-lang.org/reference/items/structs.html
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Objects
|
|
||||||
[1]: https://spec.graphql.org/October2021#sec-Execution
|
|
||||||
[2]: https://docs.rs/juniper/0.16.1/juniper/derive.GraphQLObject.html
|
|
||||||
[3]: https://docs.rs/juniper/0.16.1/juniper/attr.graphql_object.html
|
|
||||||
[4]: https://spec.graphql.org/October2021#sec-Non-Null
|
|
||||||
[5]: https://spec.graphql.org/October2021#sec-Introspection
|
|
||||||
[6]: https://doc.rust-lang.org/reference/comments.html#doc-comments
|
|
||||||
[7]: https://spec.graphql.org/October2021#sec-Descriptions
|
|
||||||
[8]: https://spec.graphql.org/October2021#sec-Input-Objects
|
|
||||||
[9]: https://spec.graphql.org/October2021#sec--deprecated
|
|
||||||
[10]: https://spec.graphql.org/October2021#sec-Enums
|
|
||||||
[11]: https://spec.graphql.org/October2021#sec-Interfaces
|
|
||||||
[12]: https://spec.graphql.org/October2021#sec-List
|
|
||||||
[13]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute
|
|
||||||
[14]: https://spec.graphql.org/October2021#sel-EAFdRDHAAEJDAoBxzT
|
|
|
@ -1,482 +0,0 @@
|
||||||
Scalars
|
|
||||||
=======
|
|
||||||
|
|
||||||
[GraphQL scalars][0] represent primitive leaf values in a GraphQL type system: numbers, strings, and booleans.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Built-in
|
|
||||||
|
|
||||||
[Juniper] provides support for all the [built-in scalars][5].
|
|
||||||
|
|
||||||
| [Rust] types | [GraphQL] scalar |
|
|
||||||
|------------------|------------------|
|
|
||||||
| `bool` | `Boolean` |
|
|
||||||
| `i32` | `Int` |
|
|
||||||
| `f64` | `Float` |
|
|
||||||
| `String`, `&str` | `String` |
|
|
||||||
| `juniper::ID` | [`ID`] |
|
|
||||||
|
|
||||||
> **NOTE**: [`ID`] scalar is [defined in the GraphQL spec][`ID`] as a type that is serialized as a string, but can be parsed from both a string and an integer.
|
|
||||||
|
|
||||||
> **TIP**: There is no built-in support for `i64`, `u64`, or other [Rust] integer types, as the [GraphQL spec doesn't define any built-in scalars for them][1] by default. Instead, to be supported, they should be defined as [custom scalars](#custom) in a [GraphQL schema][schema].
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Custom
|
|
||||||
|
|
||||||
We can create [custom scalars][2] for other primitive values, but they are still [limited in the data types for representation][1], and only introduce additional semantic meaning. This, also, often requires coordination with the client library, intended to consume the API we're building.
|
|
||||||
|
|
||||||
[Custom scalars][2] can be defined in [Juniper] by using either [`#[derive(GraphQLScalar)]`][8] or [`#[graphql_scalar]`][9] attributes, which do work pretty much the same way (except, [`#[derive(GraphQLScalar)]`][8] cannot be used on [type aliases][4]).
|
|
||||||
|
|
||||||
|
|
||||||
### Transparent delegation
|
|
||||||
|
|
||||||
Quite often, we want to create a [custom GraphQL scalar][2] type by just wrapping an existing one, inheriting all its behavior. In [Rust], this is often called as ["newtype pattern"][3]. This may be achieved by providing a `#[graphql(transparent)]` attribute to the definition:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{graphql_scalar, GraphQLScalar};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLScalar)]
|
|
||||||
#[graphql(transparent)]
|
|
||||||
pub struct UserId(i32);
|
|
||||||
|
|
||||||
// Using `#[graphql_scalar]` attribute here makes no difference, and is fully
|
|
||||||
// interchangeable with `#[derive(GraphQLScalar)]`. It's only up to the
|
|
||||||
// personal preference - which one to use.
|
|
||||||
#[graphql_scalar]
|
|
||||||
#[graphql(transparent)]
|
|
||||||
pub struct MessageId {
|
|
||||||
value: i32,
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
That's it, now the `UserId` and `MessageId` [scalars][0] can be used in [GraphQL schema][schema].
|
|
||||||
|
|
||||||
We may also customize the definition, to provide more information about our [custom scalar][2] in [GraphQL schema][schema]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::GraphQLScalar;
|
|
||||||
#
|
|
||||||
/// You can use a Rust doc comment to specify a description in GraphQL schema.
|
|
||||||
#[derive(GraphQLScalar)]
|
|
||||||
#[graphql(
|
|
||||||
transparent,
|
|
||||||
// Overwrite the name of this type in the GraphQL schema.
|
|
||||||
name = "MyUserId",
|
|
||||||
// Specifying a type description via attribute takes precedence over the
|
|
||||||
// Rust doc comment, which allows to separate Rust API docs from GraphQL
|
|
||||||
// schema descriptions, if required.
|
|
||||||
description = "Actual description.",
|
|
||||||
// Optional specification URL.
|
|
||||||
specified_by_url = "https://tools.ietf.org/html/rfc4122",
|
|
||||||
)]
|
|
||||||
pub struct UserId(String);
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Resolving
|
|
||||||
|
|
||||||
In case we need to customize [resolving][7] of a [custom GraphQL scalar][2] value (change the way it gets executed), the `#[graphql(to_output_with = <fn path>)]` attribute is the way to do so:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{GraphQLScalar, ScalarValue, Value};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLScalar)]
|
|
||||||
#[graphql(to_output_with = to_output, transparent)]
|
|
||||||
struct Incremented(i32);
|
|
||||||
|
|
||||||
/// Increments [`Incremented`] before converting into a [`Value`].
|
|
||||||
fn to_output<S: ScalarValue>(v: &Incremented) -> Value<S> {
|
|
||||||
let inc = v.0 + 1;
|
|
||||||
Value::from(inc)
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Input value parsing
|
|
||||||
|
|
||||||
Customization of a [custom GraphQL scalar][2] value parsing is possible via `#[graphql(from_input_with = <fn path>)]` attribute:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{GraphQLScalar, InputValue, ScalarValue};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLScalar)]
|
|
||||||
#[graphql(from_input_with = Self::from_input, transparent)]
|
|
||||||
struct UserId(String);
|
|
||||||
|
|
||||||
impl UserId {
|
|
||||||
/// Checks whether the [`InputValue`] is a [`String`] beginning with `id: `
|
|
||||||
/// and strips it.
|
|
||||||
fn from_input<S>(input: &InputValue<S>) -> Result<Self, String>
|
|
||||||
where
|
|
||||||
S: ScalarValue
|
|
||||||
{
|
|
||||||
input.as_string_value()
|
|
||||||
.ok_or_else(|| format!("Expected `String`, found: {input}"))
|
|
||||||
.and_then(|str| {
|
|
||||||
str.strip_prefix("id: ")
|
|
||||||
.ok_or_else(|| {
|
|
||||||
format!(
|
|
||||||
"Expected `UserId` to begin with `id: `, \
|
|
||||||
found: {input}",
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.map(|id| Self(id.to_owned()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Token parsing
|
|
||||||
|
|
||||||
Customization of which tokens a [custom GraphQL scalar][0] type should be parsed from, is possible via `#[graphql(parse_token_with = <fn path>)]` or `#[graphql(parse_token(<types>)]` attributes:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{
|
|
||||||
# GraphQLScalar, InputValue, ParseScalarResult, ParseScalarValue,
|
|
||||||
# ScalarValue, ScalarToken, Value,
|
|
||||||
# };
|
|
||||||
#
|
|
||||||
#[derive(GraphQLScalar)]
|
|
||||||
#[graphql(
|
|
||||||
to_output_with = to_output,
|
|
||||||
from_input_with = from_input,
|
|
||||||
parse_token_with = parse_token,
|
|
||||||
)]
|
|
||||||
// ^^^^^^^^^^^^^^^^ Can be replaced with `parse_token(String, i32)`, which
|
|
||||||
// tries to parse as `String` first, and then as `i32` if
|
|
||||||
// prior fails.
|
|
||||||
enum StringOrInt {
|
|
||||||
String(String),
|
|
||||||
Int(i32),
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_output<S: ScalarValue>(v: &StringOrInt) -> Value<S> {
|
|
||||||
match v {
|
|
||||||
StringOrInt::String(s) => Value::scalar(s.to_owned()),
|
|
||||||
StringOrInt::Int(i) => Value::scalar(*i),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<StringOrInt, String> {
|
|
||||||
v.as_string_value()
|
|
||||||
.map(|s| StringOrInt::String(s.into()))
|
|
||||||
.or_else(|| v.as_int_value().map(StringOrInt::Int))
|
|
||||||
.ok_or_else(|| format!("Expected `String` or `Int`, found: {v}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_token<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> {
|
|
||||||
<String as ParseScalarValue<S>>::from_str(value)
|
|
||||||
.or_else(|_| <i32 as ParseScalarValue<S>>::from_str(value))
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **NOTE**: Once we provide all 3 custom functions, there is no sense to follow [newtype pattern][3] anymore, as nothing left to inherit.
|
|
||||||
|
|
||||||
|
|
||||||
### Full behavior
|
|
||||||
|
|
||||||
Instead of providing all custom functions separately, it's possible to provide a module holding the appropriate `to_output()`, `from_input()` and `parse_token()` functions via `#[graphql(with = <module path>)]` attribute:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{
|
|
||||||
# GraphQLScalar, InputValue, ParseScalarResult, ParseScalarValue,
|
|
||||||
# ScalarValue, ScalarToken, Value,
|
|
||||||
# };
|
|
||||||
#
|
|
||||||
#[derive(GraphQLScalar)]
|
|
||||||
#[graphql(with = string_or_int)]
|
|
||||||
enum StringOrInt {
|
|
||||||
String(String),
|
|
||||||
Int(i32),
|
|
||||||
}
|
|
||||||
|
|
||||||
mod string_or_int {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
pub(super) fn to_output<S: ScalarValue>(v: &StringOrInt) -> Value<S> {
|
|
||||||
match v {
|
|
||||||
StringOrInt::String(s) => Value::scalar(s.to_owned()),
|
|
||||||
StringOrInt::Int(i) => Value::scalar(*i),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<StringOrInt, String> {
|
|
||||||
v.as_string_value()
|
|
||||||
.map(|s| StringOrInt::String(s.into()))
|
|
||||||
.or_else(|| v.as_int_value().map(StringOrInt::Int))
|
|
||||||
.ok_or_else(|| format!("Expected `String` or `Int`, found: {v}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn parse_token<S: ScalarValue>(t: ScalarToken<'_>) -> ParseScalarResult<S> {
|
|
||||||
<String as ParseScalarValue<S>>::from_str(t)
|
|
||||||
.or_else(|_| <i32 as ParseScalarValue<S>>::from_str(t))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
A regular `impl` block is also suitable for that:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{
|
|
||||||
# GraphQLScalar, InputValue, ParseScalarResult, ParseScalarValue,
|
|
||||||
# ScalarValue, ScalarToken, Value,
|
|
||||||
# };
|
|
||||||
#
|
|
||||||
#[derive(GraphQLScalar)]
|
|
||||||
// #[graphql(with = Self)] <- default behaviour, so can be omitted
|
|
||||||
enum StringOrInt {
|
|
||||||
String(String),
|
|
||||||
Int(i32),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StringOrInt {
|
|
||||||
fn to_output<S: ScalarValue>(&self) -> Value<S> {
|
|
||||||
match self {
|
|
||||||
Self::String(s) => Value::scalar(s.to_owned()),
|
|
||||||
Self::Int(i) => Value::scalar(*i),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_input<S>(v: &InputValue<S>) -> Result<Self, String>
|
|
||||||
where
|
|
||||||
S: ScalarValue
|
|
||||||
{
|
|
||||||
v.as_string_value()
|
|
||||||
.map(|s| Self::String(s.into()))
|
|
||||||
.or_else(|| v.as_int_value().map(Self::Int))
|
|
||||||
.ok_or_else(|| format!("Expected `String` or `Int`, found: {v}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_token<S>(value: ScalarToken<'_>) -> ParseScalarResult<S>
|
|
||||||
where
|
|
||||||
S: ScalarValue
|
|
||||||
{
|
|
||||||
<String as ParseScalarValue<S>>::from_str(value)
|
|
||||||
.or_else(|_| <i32 as ParseScalarValue<S>>::from_str(value))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
At the same time, any custom function still may be specified separately, if required:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{
|
|
||||||
# GraphQLScalar, InputValue, ParseScalarResult, ScalarValue,
|
|
||||||
# ScalarToken, Value
|
|
||||||
# };
|
|
||||||
#
|
|
||||||
#[derive(GraphQLScalar)]
|
|
||||||
#[graphql(
|
|
||||||
with = string_or_int,
|
|
||||||
parse_token(String, i32)
|
|
||||||
)]
|
|
||||||
enum StringOrInt {
|
|
||||||
String(String),
|
|
||||||
Int(i32),
|
|
||||||
}
|
|
||||||
|
|
||||||
mod string_or_int {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
pub(super) fn to_output<S>(v: &StringOrInt) -> Value<S>
|
|
||||||
where
|
|
||||||
S: ScalarValue,
|
|
||||||
{
|
|
||||||
match v {
|
|
||||||
StringOrInt::String(s) => Value::scalar(s.to_owned()),
|
|
||||||
StringOrInt::Int(i) => Value::scalar(*i),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn from_input<S>(v: &InputValue<S>) -> Result<StringOrInt, String>
|
|
||||||
where
|
|
||||||
S: ScalarValue,
|
|
||||||
{
|
|
||||||
v.as_string_value()
|
|
||||||
.map(|s| StringOrInt::String(s.into()))
|
|
||||||
.or_else(|| v.as_int_value().map(StringOrInt::Int))
|
|
||||||
.ok_or_else(|| format!("Expected `String` or `Int`, found: {v}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
// No need in `parse_token()` function.
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **TIP**: See more available features in the API docs of the [`#[derive(GraphQLScalar)]`][8] and [`#[graphql_scalar]`][9] attributes.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Foreign
|
|
||||||
|
|
||||||
For implementing [custom scalars][2] on foreign types there is [`#[graphql_scalar]`][9] attribute.
|
|
||||||
|
|
||||||
> **NOTE**: To satisfy [orphan rules], we should provide a local [`ScalarValue`] implementation.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# mod date {
|
|
||||||
# pub struct Date;
|
|
||||||
# impl std::str::FromStr for Date {
|
|
||||||
# type Err = String;
|
|
||||||
#
|
|
||||||
# fn from_str(_value: &str) -> Result<Self, Self::Err> {
|
|
||||||
# unimplemented!()
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
# impl std::fmt::Display for Date {
|
|
||||||
# fn fmt(&self, _f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
|
||||||
# unimplemented!()
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
# use juniper::DefaultScalarValue as CustomScalarValue;
|
|
||||||
use juniper::{graphql_scalar, InputValue, ScalarValue, Value};
|
|
||||||
|
|
||||||
#[graphql_scalar(
|
|
||||||
with = date_scalar,
|
|
||||||
parse_token(String),
|
|
||||||
scalar = CustomScalarValue,
|
|
||||||
)]
|
|
||||||
// ^^^^^^^^^^^^^^^^^ local `ScalarValue` implementation
|
|
||||||
type Date = date::Date;
|
|
||||||
// ^^^^^^^^^^ type from another crate
|
|
||||||
|
|
||||||
mod date_scalar {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
pub(super) fn to_output(v: &Date) -> Value<CustomScalarValue> {
|
|
||||||
Value::scalar(v.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn from_input(v: &InputValue<CustomScalarValue>) -> Result<Date, String> {
|
|
||||||
v.as_string_value()
|
|
||||||
.ok_or_else(|| format!("Expected `String`, found: {v}"))
|
|
||||||
.and_then(|s| s.parse().map_err(|e| format!("Failed to parse `Date`: {e}")))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Supported out-of-the-box
|
|
||||||
|
|
||||||
[Juniper] provides out-of-the-box [GraphQL scalar][0] implementations for some very common [Rust] crates. The types from these crates will be usable in your schemas automatically after enabling the correspondent self-titled [Cargo feature].
|
|
||||||
|
|
||||||
| [Rust] type | [GraphQL] scalar | [Cargo feature] |
|
|
||||||
|-----------------------------|-----------------------|------------------|
|
|
||||||
| [`bigdecimal::BigDecimal`] | `BigDecimal` | [`bigdecimal`] |
|
|
||||||
| [`bson::oid::ObjectId`] | [`ObjectID`] | [`bson`] |
|
|
||||||
| [`bson::DateTime`] | [`DateTime`] | [`bson`] |
|
|
||||||
| [`chrono::NaiveDate`] | [`LocalDate`] | [`chrono`] |
|
|
||||||
| [`chrono::NaiveTime`] | [`LocalTime`] | [`chrono`] |
|
|
||||||
| [`chrono::NaiveDateTime`] | [`LocalDateTime`] | [`chrono`] |
|
|
||||||
| [`chrono::DateTime`] | [`DateTime`] | [`chrono`] |
|
|
||||||
| [`chrono_tz::Tz`] | [`TimeZone`] | [`chrono-tz`] |
|
|
||||||
| [`rust_decimal::Decimal`] | `Decimal` | [`rust_decimal`] |
|
|
||||||
| [`jiff::civil::Date`] | [`LocalDate`] | [`jiff`] |
|
|
||||||
| [`jiff::civil::Time`] | [`LocalTime`] | [`jiff`] |
|
|
||||||
| [`jiff::civil::DateTime`] | [`LocalDateTime`] | [`jiff`] |
|
|
||||||
| [`jiff::Timestamp`] | [`DateTime`] | [`jiff`] |
|
|
||||||
| [`jiff::Zoned`] | `ZonedDateTime` | [`jiff`] |
|
|
||||||
| [`jiff::tz::TimeZone`] | `TimeZoneOrUtcOffset` | [`jiff`] |
|
|
||||||
| [`jiff::tz::TimeZone`] via [`juniper::integrations::jiff::TimeZone`] | [`TimeZone`] | [`jiff`] |
|
|
||||||
| [`jiff::tz::Offset`] | [`UtcOffset`] | [`jiff`] |
|
|
||||||
| [`jiff::Span`] | [`Duration`] | [`jiff`] |
|
|
||||||
| [`time::Date`] | [`LocalDate`] | [`time`] |
|
|
||||||
| [`time::Time`] | [`LocalTime`] | [`time`] |
|
|
||||||
| [`time::PrimitiveDateTime`] | [`LocalDateTime`] | [`time`] |
|
|
||||||
| [`time::OffsetDateTime`] | [`DateTime`] | [`time`] |
|
|
||||||
| [`time::UtcOffset`] | [`UtcOffset`] | [`time`] |
|
|
||||||
| [`url::Url`] | [`URL`] | [`url`] |
|
|
||||||
| [`uuid::Uuid`] | [`UUID`] | [`uuid`] |
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[`bigdecimal`]: https://docs.rs/bigdecimal
|
|
||||||
[`bigdecimal::BigDecimal`]: https://docs.rs/bigdecimal/latest/bigdecimal/struct.BigDecimal.html
|
|
||||||
[`bson`]: https://docs.rs/bson
|
|
||||||
[`bson::DateTime`]: https://docs.rs/bson/latest/bson/struct.DateTime.html
|
|
||||||
[`bson::oid::ObjectId`]: https://docs.rs/bson/latest/bson/oid/struct.ObjectId.html
|
|
||||||
[`chrono`]: https://docs.rs/chrono
|
|
||||||
[`chrono::DateTime`]: https://docs.rs/chrono/latest/chrono/struct.DateTime.html
|
|
||||||
[`chrono::NaiveDate`]: https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDate.html
|
|
||||||
[`chrono::NaiveDateTime`]: https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDateTime.html
|
|
||||||
[`chrono::NaiveTime`]: https://docs.rs/chrono/latest/chrono/naive/struct.NaiveTime.html
|
|
||||||
[`chrono-tz`]: https://docs.rs/chrono-tz
|
|
||||||
[`chrono_tz::Tz`]: https://docs.rs/chrono-tz/latest/chrono_tz/enum.Tz.html
|
|
||||||
[`DateTime`]: https://graphql-scalars.dev/docs/scalars/date-time
|
|
||||||
[`Duration`]: https://graphql-scalars.dev/docs/scalars/duration
|
|
||||||
[`ID`]: https://spec.graphql.org/October2021#sec-ID
|
|
||||||
[`jiff`]: https://docs.rs/jiff
|
|
||||||
[`jiff::civil::Date`]: https://docs.rs/jiff/latest/jiff/civil/struct.Date.html
|
|
||||||
[`jiff::civil::DateTime`]: https://docs.rs/jiff/latest/jiff/civil/struct.DateTime.html
|
|
||||||
[`jiff::civil::Time`]: https://docs.rs/jiff/latest/jiff/civil/struct.Time.html
|
|
||||||
[`jiff::Span`]: https://docs.rs/jiff/latest/jiff/struct.Span.html
|
|
||||||
[`jiff::Timestamp`]: https://docs.rs/jiff/latest/jiff/struct.Timestamp.html
|
|
||||||
[`jiff::tz::Offset`]: https://docs.rs/jiff/latest/jiff/tz/struct.Offset.html
|
|
||||||
[`jiff::tz::TimeZone`]: https://docs.rs/jiff/latest/jiff/tz/struct.TimeZone.html
|
|
||||||
[`jiff::Zoned`]: https://docs.rs/jiff/latest/jiff/struct.Zoned.html
|
|
||||||
[`juniper::integrations::jiff::TimeZone`]: https://docs.rs/juniper/0.16.1/juniper/integrations/jiff/struct.TimeZone.html
|
|
||||||
[`LocalDate`]: https://graphql-scalars.dev/docs/scalars/local-date
|
|
||||||
[`LocalDateTime`]: https://graphql-scalars.dev/docs/scalars/local-date-time
|
|
||||||
[`LocalTime`]: https://graphql-scalars.dev/docs/scalars/local-time
|
|
||||||
[`ObjectID`]: https://the-guild.dev/graphql/scalars/docs/scalars/object-id
|
|
||||||
[`rust_decimal`]: https://docs.rs/rust_decimal
|
|
||||||
[`rust_decimal::Decimal`]: https://docs.rs/rust_decimal/latest/rust_decimal/struct.Decimal.html
|
|
||||||
[`ScalarValue`]: https://docs.rs/juniper/0.16.1/juniper/trait.ScalarValue.html
|
|
||||||
[`serde`]: https://docs.rs/serde
|
|
||||||
[`time`]: https://docs.rs/time
|
|
||||||
[`time::Date`]: https://docs.rs/time/latest/time/struct.Date.html
|
|
||||||
[`time::PrimitiveDateTime`]: https://docs.rs/time/latest/time/struct.PrimitiveDateTime.html
|
|
||||||
[`time::Time`]: https://docs.rs/time/latest/time/struct.Time.html
|
|
||||||
[`time::UtcOffset`]: https://docs.rs/time/latest/time/struct.UtcOffset.html
|
|
||||||
[`time::OffsetDateTime`]: https://docs.rs/time/latest/time/struct.OffsetDateTime.html
|
|
||||||
[`TimeZone`]: https://graphql-scalars.dev/docs/scalars/time-zone
|
|
||||||
[`url`]: https://docs.rs/url
|
|
||||||
[`url::Url`]: https://docs.rs/url/latest/url/struct.Url.html
|
|
||||||
[`URL`]: https://graphql-scalars.dev/docs/scalars/url
|
|
||||||
[`UtcOffset`]: https://graphql-scalars.dev/docs/scalars/utc-offset
|
|
||||||
[`uuid`]: https://docs.rs/uuid
|
|
||||||
[`uuid::Uuid`]: https://docs.rs/uuid/latest/uuid/struct.Uuid.html
|
|
||||||
[`UUID`]: https://graphql-scalars.dev/docs/scalars/uuid
|
|
||||||
[Cargo feature]: https://doc.rust-lang.org/cargo/reference/features.html
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[orphan rules]: https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
[schema]: https://graphql.org/learn/schema
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Scalars
|
|
||||||
[1]: https://spec.graphql.org/October2021#sel-FAHXJDCAACKB1qb
|
|
||||||
[2]: https://spec.graphql.org/October2021#sec-Scalars.Custom-Scalars
|
|
||||||
[3]: https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html
|
|
||||||
[4]: https://doc.rust-lang.org/reference/items/type-aliases.html
|
|
||||||
[5]: https://spec.graphql.org/October2021/#sec-Scalars.Built-in-Scalars
|
|
||||||
[6]: https://serde.rs/container-attrs.html#transparent
|
|
||||||
[7]: https://spec.graphql.org/October2021#sec-Value-Resolution
|
|
||||||
[8]: https://docs.rs/juniper/0.16.1/juniper/derive.GraphQLScalar.html
|
|
||||||
[9]: https://docs.rs/juniper/0.16.1/juniper/attr.graphql_scalar.html
|
|
|
@ -1,168 +0,0 @@
|
||||||
Unions
|
|
||||||
======
|
|
||||||
|
|
||||||
> [GraphQL unions][0] represent an object that could be one of a list of [GraphQL object][10] types, but provides for no guaranteed fields between those types. They also differ from [interfaces][12] in that [object][10] types declare what [interfaces][12] they implement, but are not aware of what [unions][0] contain them.
|
|
||||||
|
|
||||||
From the server's point of view, [GraphQL unions][0] are somewhat similar to [interfaces][12]: the main difference is that they don't contain fields on their own, and so, we only need to represent a value, _dispatchable_ into concrete [objects][10].
|
|
||||||
|
|
||||||
Obviously, the most straightforward approach to express [GraphQL unions][0] in [Rust] is to use [enums][22]. In [Juniper] this may be done by using [`#[derive(GraphQLInterface)]`][2] attribute on them:
|
|
||||||
```rust
|
|
||||||
# extern crate derive_more;
|
|
||||||
# extern crate juniper;
|
|
||||||
# use derive_more::From;
|
|
||||||
# use juniper::{GraphQLObject, GraphQLUnion};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Human {
|
|
||||||
id: String,
|
|
||||||
home_planet: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Droid {
|
|
||||||
id: String,
|
|
||||||
primary_function: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(From, GraphQLUnion)]
|
|
||||||
// ^^^^ only for convenience, and may be omitted
|
|
||||||
enum Character {
|
|
||||||
Human(Human),
|
|
||||||
Droid(Droid),
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Renaming
|
|
||||||
|
|
||||||
Just as with [renaming GraphQL objects](objects/index.md#renaming), we can override the default [union][0] name by using the `#[graphql(name = "...")]` attribute:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{GraphQLObject, GraphQLUnion};
|
|
||||||
#
|
|
||||||
# #[derive(GraphQLObject)]
|
|
||||||
# struct Human {
|
|
||||||
# id: String,
|
|
||||||
# home_planet: String,
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
# #[derive(GraphQLObject)]
|
|
||||||
# struct Droid {
|
|
||||||
# id: String,
|
|
||||||
# primary_function: String,
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
#[derive(GraphQLUnion)]
|
|
||||||
#[graphql(name = "CharacterUnion")]
|
|
||||||
enum Character { // exposed as `CharacterUnion` in GraphQL schema
|
|
||||||
Human(Human),
|
|
||||||
Droid(Droid),
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **NOTE**: Unlike [Rust enum variants][22], [GraphQL union members][0] don't have any special names aside from the ones provided by [objects][10] themselves, and so, obviously, **cannot be renamed**.
|
|
||||||
|
|
||||||
|
|
||||||
### Documentation
|
|
||||||
|
|
||||||
Similarly to [documenting GraphQL objects](objects/index.md#documentation), we can [document][7] a [GraphQL union][0] via `#[graphql(description = "...")]` attribute or [Rust doc comments][6]:
|
|
||||||
```rust
|
|
||||||
# extern crate juniper;
|
|
||||||
# use juniper::{GraphQLObject, GraphQLUnion};
|
|
||||||
#
|
|
||||||
# #[derive(GraphQLObject)]
|
|
||||||
# struct Human {
|
|
||||||
# id: String,
|
|
||||||
# home_planet: String,
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
# #[derive(GraphQLObject)]
|
|
||||||
# struct Droid {
|
|
||||||
# id: String,
|
|
||||||
# primary_function: String,
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
/// This doc comment is visible in both Rust API docs and GraphQL schema
|
|
||||||
/// descriptions.
|
|
||||||
#[derive(GraphQLUnion)]
|
|
||||||
enum Character {
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
Human(Human),
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
Droid(Droid),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
#[derive(GraphQLUnion)]
|
|
||||||
#[graphql(description = "This description overwrites the one from doc comment.")]
|
|
||||||
// ^^^^^^^^^^^ or `desc` shortcut, up to your preference
|
|
||||||
enum Person {
|
|
||||||
/// This doc comment is visible only in Rust API docs.
|
|
||||||
Human(Human),
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **NOTE**: Unlike [Rust enum variants][22], [GraphQL union members][0] don't have any special constructors aside from the provided [objects][10] directly, and so, **cannot be [documented][7]**, but rather reuse [object descriptions][7] "as is".
|
|
||||||
|
|
||||||
|
|
||||||
### Ignoring
|
|
||||||
|
|
||||||
In some rare situations we may want to omit exposing an [enum][22] variant in a [GraphQL schema][1]. [Similarly to GraphQL enums](enums.md#ignoring), we can just annotate the variant with the `#[graphql(ignore)]` attribute.
|
|
||||||
|
|
||||||
As an example, let's consider the situation where we need to bind some type parameter `T` for doing interesting type-level stuff in our resolvers. To achieve this we need to have `PhantomData<T>`, but we don't want it exposed in the GraphQL schema.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# extern crate derive_more;
|
|
||||||
# extern crate juniper;
|
|
||||||
# use std::marker::PhantomData;
|
|
||||||
# use derive_more::From;
|
|
||||||
# use juniper::{GraphQLObject, GraphQLUnion};
|
|
||||||
#
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Human {
|
|
||||||
id: String,
|
|
||||||
home_planet: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct Droid {
|
|
||||||
id: String,
|
|
||||||
primary_function: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(From, GraphQLUnion)]
|
|
||||||
enum Character<S> {
|
|
||||||
Human(Human),
|
|
||||||
Droid(Droid),
|
|
||||||
#[from(ignore)]
|
|
||||||
#[graphql(ignore)]
|
|
||||||
// ^^^^^^ or `skip`, up to your preference
|
|
||||||
_State(PhantomData<S>),
|
|
||||||
}
|
|
||||||
#
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
> **WARNING**: It's the _library user's responsibility_ to ensure that ignored [enum][22] variant is **never** returned from resolvers, otherwise resolving the [GraphQL] query will **panic in runtime**.
|
|
||||||
|
|
||||||
> **TIP**: See more available features in the API docs of the [`#[derive(GraphQLUnion)]`][2] attribute.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[GraphQL]: https://graphql.org
|
|
||||||
[Juniper]: https://docs.rs/juniper
|
|
||||||
[Rust]: https://www.rust-lang.org
|
|
||||||
|
|
||||||
[0]: https://spec.graphql.org/October2021#sec-Unions
|
|
||||||
[1]: https://graphql.org/learn/schema
|
|
||||||
[2]: https://docs.rs/juniper/0.16.1/juniper/derive.GraphQLUnion.html
|
|
||||||
[6]: https://doc.rust-lang.org/reference/comments.html#doc-comments
|
|
||||||
[7]: https://spec.graphql.org/October2021#sec-Descriptions
|
|
||||||
[10]: https://spec.graphql.org/October2021#sec-Objects
|
|
||||||
[11]: https://spec.graphql.org/October2021#sec-Enums
|
|
||||||
[12]: https://spec.graphql.org/October2021#sec-Interfaces
|
|
||||||
[22]: https://doc.rust-lang.org/reference/items/enumerations.html#enumerations
|
|
1
docs/book/.gitignore
vendored
Normal file
1
docs/book/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
_rendered
|
48
docs/book/README.md
Normal file
48
docs/book/README.md
Normal file
|
@ -0,0 +1,48 @@
|
||||||
|
# Juniper Book
|
||||||
|
|
||||||
|
Book containing the Juniper documentation.
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
### Requirements
|
||||||
|
|
||||||
|
The book is built with [mdBook](https://github.com/rust-lang-nursery/mdBook).
|
||||||
|
|
||||||
|
You can install it with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo install mdbook
|
||||||
|
```
|
||||||
|
|
||||||
|
### Starting a local test server
|
||||||
|
|
||||||
|
To launch a local test server that continually re-builds the book and autoreloads the page, run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mdbook serve
|
||||||
|
```
|
||||||
|
|
||||||
|
### Building the book
|
||||||
|
|
||||||
|
You can build the book to rendered HTML with this command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mdbook build
|
||||||
|
```
|
||||||
|
|
||||||
|
The output will be in the `./_rendered` directory.
|
||||||
|
|
||||||
|
### Running the tests
|
||||||
|
|
||||||
|
To run the tests validating all code examples in the book, run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ./tests
|
||||||
|
cargo test
|
||||||
|
```
|
||||||
|
|
||||||
|
## Test setup
|
||||||
|
|
||||||
|
All Rust code examples in the book are compiled on the CI.
|
||||||
|
|
||||||
|
This is done using the [skeptic](https://github.com/budziq/rust-skeptic) library.
|
11
docs/book/book.toml
Normal file
11
docs/book/book.toml
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
[book]
|
||||||
|
title = "Juniper - GraphQL Server for Rust"
|
||||||
|
description = "Documentation for juniper, a GraphQL server library for Rust."
|
||||||
|
src = "content"
|
||||||
|
|
||||||
|
[build]
|
||||||
|
build-dir = "_rendered"
|
||||||
|
create-missing = false
|
||||||
|
|
||||||
|
[output.html]
|
||||||
|
git_repository_url = "https://github.com/graphql-rs/juniper"
|
52
docs/book/ci-build.sh
Executable file
52
docs/book/ci-build.sh
Executable file
|
@ -0,0 +1,52 @@
|
||||||
|
#! /usr/bin/env bash
|
||||||
|
|
||||||
|
# Usage: ./ci-build.sh VERSION
|
||||||
|
#
|
||||||
|
# This script builds the book to HTML with mdbook
|
||||||
|
# commits and pushes the contents to the repo in the "gh-pages" branch.
|
||||||
|
#
|
||||||
|
# It is only inteded for use on the CI!
|
||||||
|
|
||||||
|
# Enable strict error checking.
|
||||||
|
set -exo pipefail
|
||||||
|
|
||||||
|
DIR=$(dirname $(readlink -f $0))
|
||||||
|
MDBOOK="mdbook"
|
||||||
|
|
||||||
|
cd $DIR
|
||||||
|
|
||||||
|
# Verify version argument.
|
||||||
|
|
||||||
|
if [[ -z "$1" ]]; then
|
||||||
|
echo "Missing required argument 'version': cargo make build-book VERSION"
|
||||||
|
exit
|
||||||
|
fi
|
||||||
|
VERSION="$1"
|
||||||
|
|
||||||
|
# Download mdbook if not found.
|
||||||
|
|
||||||
|
if [ $MDBOOK -h ]; then
|
||||||
|
echo "mdbook found..."
|
||||||
|
else
|
||||||
|
echo "mdbook not found. Downloading..."
|
||||||
|
curl -L https://github.com/rust-lang-nursery/mdBook/releases/download/v0.2.0/mdbook-v0.2.0-x86_64-unknown-linux-gnu.tar.gz | tar xzf -
|
||||||
|
mv ./mdbook /tmp/mdbook
|
||||||
|
MDBOOK="/tmp/mdbook"
|
||||||
|
fi
|
||||||
|
|
||||||
|
$MDBOOK build
|
||||||
|
echo $VERSION > ./_rendered/VERSION
|
||||||
|
rm -rf /tmp/book-content
|
||||||
|
mv ./_rendered /tmp/book-content
|
||||||
|
|
||||||
|
cd $DIR/../..
|
||||||
|
git clean -fd
|
||||||
|
git checkout gh-pages
|
||||||
|
rm -rf $VERSION
|
||||||
|
mv /tmp/book-content ./$VERSION
|
||||||
|
git remote set-url --push origin git@github.com:graphql-rust/juniper.git
|
||||||
|
git config --local user.name "Juniper Bot"
|
||||||
|
git config --local user.email "juniper@example.com"
|
||||||
|
git add -A $VERSION
|
||||||
|
git diff-index --quiet HEAD || git commit -m "Updated book for $VERSION ***NO_CI***"
|
||||||
|
git push origin gh-pages
|
76
docs/book/content/README.md
Normal file
76
docs/book/content/README.md
Normal file
|
@ -0,0 +1,76 @@
|
||||||
|
# Juniper
|
||||||
|
|
||||||
|
Juniper is a [GraphQL] server library for Rust. Build type-safe and fast API
|
||||||
|
servers with minimal boilerplate and configuration.
|
||||||
|
|
||||||
|
[GraphQL][graphql] is a data query language developed by Facebook intended to
|
||||||
|
serve mobile and web application frontends.
|
||||||
|
|
||||||
|
_Juniper_ makes it possible to write GraphQL servers in Rust that are
|
||||||
|
type-safe and blazingly fast. We also try to make declaring and resolving
|
||||||
|
GraphQL schemas as convenient as possible as Rust will allow.
|
||||||
|
|
||||||
|
Juniper does not include a web server - instead it provides building blocks to
|
||||||
|
make integration with existing servers straightforward. It optionally provides a
|
||||||
|
pre-built integration for the [Hyper][hyper], [Iron][iron], [Rocket], and [Warp][warp] frameworks, including
|
||||||
|
embedded [Graphiql][graphiql] for easy debugging.
|
||||||
|
|
||||||
|
- [Cargo crate](https://crates.io/crates/juniper)
|
||||||
|
- [API Reference][docsrs]
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
Juniper supports the full GraphQL query language according to the
|
||||||
|
[specification][graphql_spec], including interfaces, unions, schema
|
||||||
|
introspection, and validations.
|
||||||
|
It does not, however, support the schema language.
|
||||||
|
|
||||||
|
As an exception to other GraphQL libraries for other languages, Juniper builds
|
||||||
|
non-null types by default. A field of type `Vec<Episode>` will be converted into
|
||||||
|
`[Episode!]!`. The corresponding Rust type for e.g. `[Episode]` would be
|
||||||
|
`Option<Vec<Option<Episode>>>`.
|
||||||
|
|
||||||
|
## Integrations
|
||||||
|
|
||||||
|
### Data types
|
||||||
|
|
||||||
|
Juniper has automatic integration with some very common Rust crates to make
|
||||||
|
building schemas a breeze. The types from these crates will be usable in
|
||||||
|
your Schemas automatically.
|
||||||
|
|
||||||
|
- [uuid][uuid]
|
||||||
|
- [url][url]
|
||||||
|
- [chrono][chrono]
|
||||||
|
- [bson][bson]
|
||||||
|
|
||||||
|
### Web Frameworks
|
||||||
|
|
||||||
|
- [hyper][hyper]
|
||||||
|
- [rocket][rocket]
|
||||||
|
- [iron][iron]
|
||||||
|
- [warp][warp]
|
||||||
|
|
||||||
|
## API Stability
|
||||||
|
|
||||||
|
Juniper has not reached 1.0 yet, thus some API instability should be expected.
|
||||||
|
|
||||||
|
[graphql]: http://graphql.org
|
||||||
|
[graphiql]: https://github.com/graphql/graphiql
|
||||||
|
[iron]: https://github.com/iron/iron
|
||||||
|
[graphql_spec]: http://facebook.github.io/graphql
|
||||||
|
[test_schema_rs]: https://github.com/graphql-rust/juniper/blob/master/juniper/src/tests/schema.rs
|
||||||
|
[tokio]: https://github.com/tokio-rs/tokio
|
||||||
|
[hyper_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_hyper/examples
|
||||||
|
[rocket_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_rocket/examples
|
||||||
|
[iron_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_iron/examples
|
||||||
|
[hyper]: https://hyper.rs
|
||||||
|
[rocket]: https://rocket.rs
|
||||||
|
[book]: https://graphql-rust.github.io
|
||||||
|
[book_quickstart]: https://graphql-rust.github.io/quickstart.html
|
||||||
|
[docsrs]: https://docs.rs/juniper
|
||||||
|
[warp]: https://github.com/seanmonstar/warp
|
||||||
|
[warp_examples]: https://github.com/graphql-rust/juniper/tree/master/juniper_warp/examples
|
||||||
|
[uuid]: https://crates.io/crates/uuid
|
||||||
|
[url]: https://crates.io/crates/url
|
||||||
|
[chrono]: https://crates.io/crates/chrono
|
||||||
|
[bson]: https://crates.io/crates/bson
|
40
docs/book/content/SUMMARY.md
Normal file
40
docs/book/content/SUMMARY.md
Normal file
|
@ -0,0 +1,40 @@
|
||||||
|
- [Introduction](README.md)
|
||||||
|
- [Quickstart](quickstart.md)
|
||||||
|
|
||||||
|
- [Type System](types/index.md)
|
||||||
|
|
||||||
|
- [Defining objects](types/objects/defining_objects.md)
|
||||||
|
- [Complex fields](types/objects/complex_fields.md)
|
||||||
|
- [Using contexts](types/objects/using_contexts.md)
|
||||||
|
- [Error handling](types/objects/error_handling.md)
|
||||||
|
- [Other types](types/other-index.md)
|
||||||
|
- [Enums](types/enums.md)
|
||||||
|
- [Interfaces](types/interfaces.md)
|
||||||
|
- [Input objects](types/input_objects.md)
|
||||||
|
- [Scalars](types/scalars.md)
|
||||||
|
- [Unions](types/unions.md)
|
||||||
|
|
||||||
|
- [Schemas and mutations](schema/schemas_and_mutations.md)
|
||||||
|
|
||||||
|
- [Adding A Server](servers/index.md)
|
||||||
|
|
||||||
|
- [Official Server Integrations](servers/official.md) - [Hyper](servers/hyper.md)
|
||||||
|
- [Warp](servers/warp.md)
|
||||||
|
- [Rocket](servers/rocket.md)
|
||||||
|
- [Iron](servers/iron.md)
|
||||||
|
- [Hyper](servers/hyper.md)
|
||||||
|
- [Third Party Integrations](servers/third-party.md)
|
||||||
|
|
||||||
|
- [Advanced Topics](advanced/index.md)
|
||||||
|
|
||||||
|
- [Introspection](advanced/introspection.md)
|
||||||
|
- [Non-struct objects](advanced/non_struct_objects.md)
|
||||||
|
- [Implicit and explicit null](advanced/implicit_and_explicit_null.md)
|
||||||
|
- [Objects and generics](advanced/objects_and_generics.md)
|
||||||
|
- [Multiple operations per request](advanced/multiple_ops_per_request.md)
|
||||||
|
- [Dataloaders](advanced/dataloaders.md)
|
||||||
|
- [Subscriptions](advanced/subscriptions.md)
|
||||||
|
|
||||||
|
# - [Context switching]
|
||||||
|
|
||||||
|
# - [Dynamic type system]
|
194
docs/book/content/advanced/dataloaders.md
Normal file
194
docs/book/content/advanced/dataloaders.md
Normal file
|
@ -0,0 +1,194 @@
|
||||||
|
# Avoiding the N+1 Problem With Dataloaders
|
||||||
|
|
||||||
|
A common issue with graphql servers is how the resolvers query their datasource.
|
||||||
|
This issue results in a large number of unneccessary database queries or http requests.
|
||||||
|
Say you were wanting to list a bunch of cults people were in
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
query {
|
||||||
|
persons {
|
||||||
|
id
|
||||||
|
name
|
||||||
|
cult {
|
||||||
|
id
|
||||||
|
name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
What would be executed by a SQL database would be:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT id, name, cult_id FROM persons;
|
||||||
|
SELECT id, name FROM cults WHERE id = 1;
|
||||||
|
SELECT id, name FROM cults WHERE id = 1;
|
||||||
|
SELECT id, name FROM cults WHERE id = 1;
|
||||||
|
SELECT id, name FROM cults WHERE id = 1;
|
||||||
|
SELECT id, name FROM cults WHERE id = 2;
|
||||||
|
SELECT id, name FROM cults WHERE id = 2;
|
||||||
|
SELECT id, name FROM cults WHERE id = 2;
|
||||||
|
# ...
|
||||||
|
```
|
||||||
|
|
||||||
|
Once the list of users has been returned, a separate query is run to find the cult of each user.
|
||||||
|
You can see how this could quickly become a problem.
|
||||||
|
|
||||||
|
A common solution to this is to introduce a **dataloader**.
|
||||||
|
This can be done with Juniper using the crate [cksac/dataloader-rs](https://github.com/cksac/dataloader-rs), which has two types of dataloaders; cached and non-cached.
|
||||||
|
|
||||||
|
#### Cached Loader
|
||||||
|
DataLoader provides a memoization cache, after .load() is called once with a given key, the resulting value is cached to eliminate redundant loads.
|
||||||
|
|
||||||
|
DataLoader caching does not replace Redis, Memcache, or any other shared application-level cache. DataLoader is first and foremost a data loading mechanism, and its cache only serves the purpose of not repeatedly loading the same data in the context of a single request to your Application. [(read more)](https://github.com/graphql/dataloader#caching)
|
||||||
|
|
||||||
|
### What does it look like?
|
||||||
|
|
||||||
|
!FILENAME Cargo.toml
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
actix-identity = "0.4.0-beta.4"
|
||||||
|
actix-rt = "1.0"
|
||||||
|
actix-web = {version = "2.0", features = []}
|
||||||
|
juniper = { git = "https://github.com/graphql-rust/juniper" }
|
||||||
|
futures = "0.3"
|
||||||
|
postgres = "0.15.2"
|
||||||
|
dataloader = "0.12.0"
|
||||||
|
async-trait = "0.1.30"
|
||||||
|
```
|
||||||
|
|
||||||
|
```rust, ignore
|
||||||
|
// use dataloader::cached::Loader;
|
||||||
|
use dataloader::non_cached::Loader;
|
||||||
|
use dataloader::BatchFn;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use postgres::{Connection, TlsMode};
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
pub fn get_db_conn() -> Connection {
|
||||||
|
let pg_connection_string = env::var("DATABASE_URI").expect("need a db uri");
|
||||||
|
println!("Connecting to {}", pg_connection_string);
|
||||||
|
let conn = Connection::connect(&pg_connection_string[..], TlsMode::None).unwrap();
|
||||||
|
println!("Connection is fine");
|
||||||
|
conn
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Cult {
|
||||||
|
pub id: i32,
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_cult_by_ids(hashmap: &mut HashMap<i32, Cult>, ids: Vec<i32>) {
|
||||||
|
let conn = get_db_conn();
|
||||||
|
for row in &conn
|
||||||
|
.query("SELECT id, name FROM cults WHERE id = ANY($1)", &[&ids])
|
||||||
|
.unwrap()
|
||||||
|
{
|
||||||
|
let cult = Cult {
|
||||||
|
id: row.get(0),
|
||||||
|
name: row.get(1),
|
||||||
|
};
|
||||||
|
hashmap.insert(cult.id, cult);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CultBatcher;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl BatchFn<i32, Cult> for CultBatcher {
|
||||||
|
|
||||||
|
// A hashmap is used, as we need to return an array which maps each original key to a Cult.
|
||||||
|
async fn load(&self, keys: &[i32]) -> HashMap<i32, Cult> {
|
||||||
|
println!("load cult batch {:?}", keys);
|
||||||
|
let mut cult_hashmap = HashMap::new();
|
||||||
|
get_cult_by_ids(&mut cult_hashmap, keys.to_vec());
|
||||||
|
cult_hashmap
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type CultLoader = Loader<i32, Cult, CultBatcher>;
|
||||||
|
|
||||||
|
// To create a new loader
|
||||||
|
pub fn get_loader() -> CultLoader {
|
||||||
|
Loader::new(CultBatcher)
|
||||||
|
// Usually a DataLoader will coalesce all individual loads which occur
|
||||||
|
// within a single frame of execution before calling your batch function with all requested keys.
|
||||||
|
// However sometimes this behavior is not desirable or optimal.
|
||||||
|
// Perhaps you expect requests to be spread out over a few subsequent ticks
|
||||||
|
// See: https://github.com/cksac/dataloader-rs/issues/12
|
||||||
|
// More info: https://github.com/graphql/dataloader#batch-scheduling
|
||||||
|
// A larger yield count will allow more requests to append to batch but will wait longer before actual load.
|
||||||
|
.with_yield_count(100)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[juniper::graphql_object(Context = Context)]
|
||||||
|
impl Cult {
|
||||||
|
// your resolvers
|
||||||
|
|
||||||
|
// To call the dataloader
|
||||||
|
pub async fn cult_by_id(ctx: &Context, id: i32) -> Cult {
|
||||||
|
ctx.cult_loader.load(id).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
### How do I call them?
|
||||||
|
|
||||||
|
Once created, a dataloader has the async functions `.load()` and `.load_many()`.
|
||||||
|
In the above example `cult_loader.load(id: i32).await` returns `Cult`. If we had used `cult_loader.load_many(Vec<i32>).await` it would have returned `Vec<Cult>`.
|
||||||
|
|
||||||
|
|
||||||
|
### Where do I create my dataloaders?
|
||||||
|
|
||||||
|
**Dataloaders** should be created per-request to avoid risk of bugs where one user is able to load cached/batched data from another user/ outside of its authenticated scope.
|
||||||
|
Creating dataloaders within individual resolvers will prevent batching from occurring and will nullify the benefits of the dataloader.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
_When you declare your context_
|
||||||
|
```rust, ignore
|
||||||
|
use juniper;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Context {
|
||||||
|
pub cult_loader: CultLoader,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl juniper::Context for Context {}
|
||||||
|
|
||||||
|
impl Context {
|
||||||
|
pub fn new(cult_loader: CultLoader) -> Self {
|
||||||
|
Self {
|
||||||
|
cult_loader
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
_Your handler for GraphQL (Note: instantiating context here keeps it per-request)_
|
||||||
|
```rust, ignore
|
||||||
|
pub async fn graphql(
|
||||||
|
st: web::Data<Arc<Schema>>,
|
||||||
|
data: web::Json<GraphQLRequest>,
|
||||||
|
) -> Result<HttpResponse, Error> {
|
||||||
|
|
||||||
|
// Context setup
|
||||||
|
let cult_loader = get_loader();
|
||||||
|
let ctx = Context::new(cult_loader);
|
||||||
|
|
||||||
|
// Execute
|
||||||
|
let res = data.execute(&st, &ctx).await;
|
||||||
|
let json = serde_json::to_string(&res).map_err(error::ErrorInternalServerError)?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok()
|
||||||
|
.content_type("application/json")
|
||||||
|
.body(json))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Further Example:
|
||||||
|
|
||||||
|
For a full example using Dataloaders and Context check out [jayy-lmao/rust-graphql-docker](https://github.com/jayy-lmao/rust-graphql-docker).
|
117
docs/book/content/advanced/implicit_and_explicit_null.md
Normal file
117
docs/book/content/advanced/implicit_and_explicit_null.md
Normal file
|
@ -0,0 +1,117 @@
|
||||||
|
# Implicit and explicit null
|
||||||
|
|
||||||
|
There are two ways that a client can submit a null argument or field in a query.
|
||||||
|
|
||||||
|
They can use a null literal:
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
{
|
||||||
|
field(arg: null)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Or they can simply omit the argument:
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
{
|
||||||
|
field
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The former is an explicit null and the latter is an implicit null.
|
||||||
|
|
||||||
|
There are some situations where it's useful to know which one the user provided.
|
||||||
|
|
||||||
|
For example, let's say your business logic has a function that allows users to
|
||||||
|
perform a "patch" operation on themselves. Let's say your users can optionally
|
||||||
|
have favorite and least favorite numbers, and the input for that might look
|
||||||
|
like this:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
/// Updates user attributes. Fields that are `None` are left as-is.
|
||||||
|
pub struct UserPatch {
|
||||||
|
/// If `Some`, updates the user's favorite number.
|
||||||
|
pub favorite_number: Option<Option<i32>>,
|
||||||
|
|
||||||
|
/// If `Some`, updates the user's least favorite number.
|
||||||
|
pub least_favorite_number: Option<Option<i32>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
To set a user's favorite number to 7, you would set `favorite_number` to
|
||||||
|
`Some(Some(7))`. In GraphQL, that might look like this:
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
mutation { patchUser(patch: { favoriteNumber: 7 }) }
|
||||||
|
```
|
||||||
|
|
||||||
|
To unset the user's favorite number, you would set `favorite_number` to
|
||||||
|
`Some(None)`. In GraphQL, that might look like this:
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
mutation { patchUser(patch: { favoriteNumber: null }) }
|
||||||
|
```
|
||||||
|
|
||||||
|
If you want to leave the user's favorite number alone, you would set it to
|
||||||
|
`None`. In GraphQL, that might look like this:
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
mutation { patchUser(patch: {}) }
|
||||||
|
```
|
||||||
|
|
||||||
|
The last two cases rely on being able to distinguish between explicit and implicit null.
|
||||||
|
|
||||||
|
In Juniper, this can be done using the `Nullable` type:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::{FieldResult, Nullable};
|
||||||
|
|
||||||
|
#[derive(juniper::GraphQLInputObject)]
|
||||||
|
struct UserPatchInput {
|
||||||
|
pub favorite_number: Nullable<i32>,
|
||||||
|
pub least_favorite_number: Nullable<i32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Into<UserPatch> for UserPatchInput {
|
||||||
|
fn into(self) -> UserPatch {
|
||||||
|
UserPatch {
|
||||||
|
// The `explicit` function transforms the `Nullable` into an
|
||||||
|
// `Option<Option<T>>` as expected by the business logic layer.
|
||||||
|
favorite_number: self.favorite_number.explicit(),
|
||||||
|
least_favorite_number: self.least_favorite_number.explicit(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# pub struct UserPatch {
|
||||||
|
# pub favorite_number: Option<Option<i32>>,
|
||||||
|
# pub least_favorite_number: Option<Option<i32>>,
|
||||||
|
# }
|
||||||
|
|
||||||
|
# struct Session;
|
||||||
|
# impl Session {
|
||||||
|
# fn patch_user(&self, _patch: UserPatch) -> FieldResult<()> { Ok(()) }
|
||||||
|
# }
|
||||||
|
|
||||||
|
struct Context {
|
||||||
|
session: Session,
|
||||||
|
}
|
||||||
|
impl juniper::Context for Context {}
|
||||||
|
|
||||||
|
struct Mutation;
|
||||||
|
|
||||||
|
#[juniper::graphql_object(context = Context)]
|
||||||
|
impl Mutation {
|
||||||
|
fn patch_user(ctx: &Context, patch: UserPatchInput) -> FieldResult<bool> {
|
||||||
|
ctx.session.patch_user(patch.into())?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
This type functions much like `Option`, but has two empty variants so you can
|
||||||
|
distinguish between implicit and explicit null.
|
11
docs/book/content/advanced/index.md
Normal file
11
docs/book/content/advanced/index.md
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
# Advanced Topics
|
||||||
|
|
||||||
|
The chapters below cover some more advanced scenarios.
|
||||||
|
|
||||||
|
- [Introspection](introspection.md)
|
||||||
|
- [Non-struct objects](non_struct_objects.md)
|
||||||
|
- [Implicit and explicit null](implicit_and_explicit_null.md)
|
||||||
|
- [Objects and generics](objects_and_generics.md)
|
||||||
|
- [Multiple operations per request](multiple_ops_per_request.md)
|
||||||
|
- [Dataloaders](dataloaders.md)
|
||||||
|
- [Subscriptions](subscriptions.md)
|
82
docs/book/content/advanced/introspection.md
Normal file
82
docs/book/content/advanced/introspection.md
Normal file
|
@ -0,0 +1,82 @@
|
||||||
|
# Introspection
|
||||||
|
|
||||||
|
GraphQL defines a special built-in top-level field called `__schema`. Querying
|
||||||
|
for this field allows one to [introspect the schema](https://graphql.org/learn/introspection/)
|
||||||
|
at runtime to see what queries and mutations the GraphQL server supports.
|
||||||
|
|
||||||
|
Because introspection queries are just regular GraphQL queries, Juniper supports
|
||||||
|
them natively. For example, to get all the names of the types supported one
|
||||||
|
could execute the following query against Juniper:
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
{
|
||||||
|
__schema {
|
||||||
|
types {
|
||||||
|
name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Schema introspection output as JSON
|
||||||
|
|
||||||
|
Many client libraries and tools in the GraphQL ecosystem require a complete
|
||||||
|
representation of the server schema. Often this representation is in JSON and
|
||||||
|
referred to as `schema.json`. A complete representation of the schema can be
|
||||||
|
produced by issuing a specially crafted introspection query.
|
||||||
|
|
||||||
|
Juniper provides a convenience function to introspect the entire schema. The
|
||||||
|
result can then be converted to JSON for use with tools and libraries such as
|
||||||
|
[graphql-client](https://github.com/graphql-rust/graphql-client):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(unused_variables)]
|
||||||
|
# extern crate juniper;
|
||||||
|
# extern crate serde_json;
|
||||||
|
use juniper::{
|
||||||
|
graphql_object, EmptyMutation, EmptySubscription, FieldResult,
|
||||||
|
GraphQLObject, IntrospectionFormat,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Define our schema.
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Example {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Context;
|
||||||
|
impl juniper::Context for Context {}
|
||||||
|
|
||||||
|
struct Query;
|
||||||
|
|
||||||
|
#[graphql_object(context = Context)]
|
||||||
|
impl Query {
|
||||||
|
fn example(id: String) -> FieldResult<Example> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Schema = juniper::RootNode<
|
||||||
|
'static,
|
||||||
|
Query,
|
||||||
|
EmptyMutation<Context>,
|
||||||
|
EmptySubscription<Context>
|
||||||
|
>;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// Create a context object.
|
||||||
|
let ctx = Context{};
|
||||||
|
|
||||||
|
// Run the built-in introspection query.
|
||||||
|
let (res, _errors) = juniper::introspect(
|
||||||
|
&Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()),
|
||||||
|
&ctx,
|
||||||
|
IntrospectionFormat::default(),
|
||||||
|
).unwrap();
|
||||||
|
|
||||||
|
// Convert introspection result to json.
|
||||||
|
let json_result = serde_json::to_string_pretty(&res);
|
||||||
|
assert!(json_result.is_ok());
|
||||||
|
}
|
||||||
|
```
|
73
docs/book/content/advanced/multiple_ops_per_request.md
Normal file
73
docs/book/content/advanced/multiple_ops_per_request.md
Normal file
|
@ -0,0 +1,73 @@
|
||||||
|
# Multiple operations per request
|
||||||
|
|
||||||
|
The GraphQL standard generally assumes there will be one server request for each client operation you want to perform (such as a query or mutation). This is conceptually simple but has the potential to be inefficent.
|
||||||
|
|
||||||
|
Some client libraries such as [apollo-link-batch-http](https://www.apollographql.com/docs/link/links/batch-http.html) have added the ability to batch operations in a single HTTP request to save network round-trips and potentially increase performance. There are some [tradeoffs](https://blog.apollographql.com/batching-client-graphql-queries-a685f5bcd41b) that should be considered before batching requests.
|
||||||
|
|
||||||
|
Juniper's server integration crates support multiple operations in a single HTTP request using JSON arrays. This makes them compatible with client libraries that support batch operations without any special configuration.
|
||||||
|
|
||||||
|
Server integration crates maintained by others are **not required** to support batch requests. Batch requests aren't part of the official GraphQL specification.
|
||||||
|
|
||||||
|
Assuming an integration supports batch requests, for the following GraphQL query:
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
{
|
||||||
|
hero {
|
||||||
|
name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The json data to POST to the server for an individual request would be:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"query": "{hero{name}}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
And the response would be of the form:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"hero": {
|
||||||
|
"name": "R2-D2"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If you wanted to run the same query twice in a single HTTP request, the batched json data to POST to the server would be:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"query": "{hero{name}}"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"query": "{hero{name}}"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
And the response would be of the form:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"hero": {
|
||||||
|
"name": "R2-D2"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"hero": {
|
||||||
|
"name": "R2-D2"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
58
docs/book/content/advanced/non_struct_objects.md
Normal file
58
docs/book/content/advanced/non_struct_objects.md
Normal file
|
@ -0,0 +1,58 @@
|
||||||
|
# Non-struct objects
|
||||||
|
|
||||||
|
Up until now, we've only looked at mapping structs to GraphQL objects. However,
|
||||||
|
any Rust type can be mapped into a GraphQL object. In this chapter, we'll look
|
||||||
|
at enums, but traits will work too - they don't _have_ to be mapped into GraphQL
|
||||||
|
interfaces.
|
||||||
|
|
||||||
|
Using `Result`-like enums can be a useful way of reporting e.g. validation
|
||||||
|
errors from a mutation:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::{graphql_object, GraphQLObject};
|
||||||
|
# #[derive(juniper::GraphQLObject)] struct User { name: String }
|
||||||
|
#
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct ValidationError {
|
||||||
|
field: String,
|
||||||
|
message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
# #[allow(dead_code)]
|
||||||
|
enum SignUpResult {
|
||||||
|
Ok(User),
|
||||||
|
Error(Vec<ValidationError>),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[graphql_object]
|
||||||
|
impl SignUpResult {
|
||||||
|
fn user(&self) -> Option<&User> {
|
||||||
|
match *self {
|
||||||
|
SignUpResult::Ok(ref user) => Some(user),
|
||||||
|
SignUpResult::Error(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error(&self) -> Option<&Vec<ValidationError>> {
|
||||||
|
match *self {
|
||||||
|
SignUpResult::Ok(_) => None,
|
||||||
|
SignUpResult::Error(ref errors) => Some(errors)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
Here, we use an enum to decide whether a user's input data was valid or not, and
|
||||||
|
it could be used as the result of e.g. a sign up mutation.
|
||||||
|
|
||||||
|
While this is an example of how you could use something other than a struct to
|
||||||
|
represent a GraphQL object, it's also an example on how you could implement
|
||||||
|
error handling for "expected" errors - errors like validation errors. There are
|
||||||
|
no hard rules on how to represent errors in GraphQL, but there are
|
||||||
|
[some](https://github.com/facebook/graphql/issues/117#issuecomment-170180628)
|
||||||
|
[comments](https://github.com/graphql/graphql-js/issues/560#issuecomment-259508214)
|
||||||
|
from one of the authors of GraphQL on how they intended "hard" field errors to
|
||||||
|
be used, and how to model expected errors.
|
66
docs/book/content/advanced/objects_and_generics.md
Normal file
66
docs/book/content/advanced/objects_and_generics.md
Normal file
|
@ -0,0 +1,66 @@
|
||||||
|
# Objects and generics
|
||||||
|
|
||||||
|
Yet another point where GraphQL and Rust differs is in how generics work. In
|
||||||
|
Rust, almost any type could be generic - that is, take type parameters. In
|
||||||
|
GraphQL, there are only two generic types: lists and non-nullables.
|
||||||
|
|
||||||
|
This poses a restriction on what you can expose in GraphQL from Rust: no generic
|
||||||
|
structs can be exposed - all type parameters must be bound. For example, you can
|
||||||
|
not make e.g. `Result<T, E>` into a GraphQL type, but you _can_ make e.g.
|
||||||
|
`Result<User, String>` into a GraphQL type.
|
||||||
|
|
||||||
|
Let's make a slightly more compact but generic implementation of [the last
|
||||||
|
chapter](non_struct_objects.md):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# #[derive(juniper::GraphQLObject)] struct User { name: String }
|
||||||
|
# #[derive(juniper::GraphQLObject)] struct ForumPost { title: String }
|
||||||
|
|
||||||
|
#[derive(juniper::GraphQLObject)]
|
||||||
|
struct ValidationError {
|
||||||
|
field: String,
|
||||||
|
message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
# #[allow(dead_code)]
|
||||||
|
struct MutationResult<T>(Result<T, Vec<ValidationError>>);
|
||||||
|
|
||||||
|
#[juniper::graphql_object(
|
||||||
|
name = "UserResult",
|
||||||
|
)]
|
||||||
|
impl MutationResult<User> {
|
||||||
|
fn user(&self) -> Option<&User> {
|
||||||
|
self.0.as_ref().ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error(&self) -> Option<&Vec<ValidationError>> {
|
||||||
|
self.0.as_ref().err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[juniper::graphql_object(
|
||||||
|
name = "ForumPostResult",
|
||||||
|
)]
|
||||||
|
impl MutationResult<ForumPost> {
|
||||||
|
fn forum_post(&self) -> Option<&ForumPost> {
|
||||||
|
self.0.as_ref().ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error(&self) -> Option<&Vec<ValidationError>> {
|
||||||
|
self.0.as_ref().err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
Here, we've made a wrapper around `Result` and exposed some concrete
|
||||||
|
instantiations of `Result<T, E>` as distinct GraphQL objects. The reason we
|
||||||
|
needed the wrapper is of Rust's rules for when you can derive a trait - in this
|
||||||
|
case, both `Result` and Juniper's internal GraphQL trait are from third-party
|
||||||
|
sources.
|
||||||
|
|
||||||
|
Because we're using generics, we also need to specify a name for our
|
||||||
|
instantiated types. Even if Juniper _could_ figure out the name,
|
||||||
|
`MutationResult<User>` wouldn't be a valid GraphQL type name.
|
174
docs/book/content/advanced/subscriptions.md
Normal file
174
docs/book/content/advanced/subscriptions.md
Normal file
|
@ -0,0 +1,174 @@
|
||||||
|
# Subscriptions
|
||||||
|
### How to achieve realtime data with GraphQL subscriptions
|
||||||
|
|
||||||
|
GraphQL subscriptions are a way to push data from the server to clients requesting real-time messages
|
||||||
|
from the server. Subscriptions are similar to queries in that they specify a set of fields to be delivered to the client,
|
||||||
|
but instead of immediately returning a single answer a result is sent every time a particular event happens on the
|
||||||
|
server.
|
||||||
|
|
||||||
|
In order to execute subscriptions you need a coordinator (that spawns connections)
|
||||||
|
and a GraphQL object that can be resolved into a stream--elements of which will then
|
||||||
|
be returned to the end user. The [`juniper_subscriptions`][juniper_subscriptions] crate
|
||||||
|
provides a default connection implementation. Currently subscriptions are only supported on the `master` branch. Add the following to your `Cargo.toml`:
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
juniper = { git = "https://github.com/graphql-rust/juniper", branch = "master" }
|
||||||
|
juniper_subscriptions = { git = "https://github.com/graphql-rust/juniper", branch = "master" }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Schema Definition
|
||||||
|
|
||||||
|
The `Subscription` is just a GraphQL object, similar to the query root and mutations object that you defined for the
|
||||||
|
operations in your [Schema][Schema]. For subscriptions all fields/operations should be async and should return a [Stream][Stream].
|
||||||
|
|
||||||
|
This example shows a subscription operation that returns two events, the strings `Hello` and `World!`
|
||||||
|
sequentially:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# use juniper::{graphql_object, graphql_subscription, FieldError};
|
||||||
|
# use futures::Stream;
|
||||||
|
# use std::pin::Pin;
|
||||||
|
#
|
||||||
|
# #[derive(Clone)]
|
||||||
|
# pub struct Database;
|
||||||
|
# impl juniper::Context for Database {}
|
||||||
|
|
||||||
|
# pub struct Query;
|
||||||
|
# #[graphql_object(context = Database)]
|
||||||
|
# impl Query {
|
||||||
|
# fn hello_world() -> &'static str {
|
||||||
|
# "Hello World!"
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
pub struct Subscription;
|
||||||
|
|
||||||
|
type StringStream = Pin<Box<dyn Stream<Item = Result<String, FieldError>> + Send>>;
|
||||||
|
|
||||||
|
#[graphql_subscription(context = Database)]
|
||||||
|
impl Subscription {
|
||||||
|
async fn hello_world() -> StringStream {
|
||||||
|
let stream = futures::stream::iter(vec![
|
||||||
|
Ok(String::from("Hello")),
|
||||||
|
Ok(String::from("World!"))
|
||||||
|
]);
|
||||||
|
Box::pin(stream)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main () {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### Coordinator
|
||||||
|
|
||||||
|
Subscriptions require a bit more resources than regular queries and provide a great vector for DOS attacks. This can can bring down a server easily if not handled correctly. The [`SubscriptionCoordinator`][SubscriptionCoordinator] trait provides coordination logic to enable functionality like DOS attack mitigation and resource limits.
|
||||||
|
|
||||||
|
The [`SubscriptionCoordinator`][SubscriptionCoordinator] contains the schema and can keep track of opened connections, handle subscription
|
||||||
|
start and end, and maintain a global subscription id for each subscription. Each time a connection is established,
|
||||||
|
the [`SubscriptionCoordinator`][SubscriptionCoordinator] spawns a [`SubscriptionConnection`][SubscriptionConnection]. The [`SubscriptionConnection`][SubscriptionConnection] handles a single connection, providing resolver logic for a client stream as well as reconnection
|
||||||
|
and shutdown logic.
|
||||||
|
|
||||||
|
|
||||||
|
While you can implement [`SubscriptionCoordinator`][SubscriptionCoordinator] yourself, Juniper contains a simple and generic implementation called [`Coordinator`][Coordinator]. The `subscribe`
|
||||||
|
operation returns a [`Future`][Future] with an `Item` value of a `Result<Connection, GraphQLError>`,
|
||||||
|
where [`Connection`][Connection] is a `Stream` of values returned by the operation and [`GraphQLError`][GraphQLError] is the error when the subscription fails.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(dead_code)]
|
||||||
|
# extern crate futures;
|
||||||
|
# extern crate juniper;
|
||||||
|
# extern crate juniper_subscriptions;
|
||||||
|
# extern crate serde_json;
|
||||||
|
# extern crate tokio;
|
||||||
|
# use juniper::{
|
||||||
|
# http::GraphQLRequest,
|
||||||
|
# graphql_object, graphql_subscription,
|
||||||
|
# DefaultScalarValue, EmptyMutation, FieldError,
|
||||||
|
# RootNode, SubscriptionCoordinator,
|
||||||
|
# };
|
||||||
|
# use juniper_subscriptions::Coordinator;
|
||||||
|
# use futures::{Stream, StreamExt};
|
||||||
|
# use std::pin::Pin;
|
||||||
|
#
|
||||||
|
# #[derive(Clone)]
|
||||||
|
# pub struct Database;
|
||||||
|
#
|
||||||
|
# impl juniper::Context for Database {}
|
||||||
|
#
|
||||||
|
# impl Database {
|
||||||
|
# fn new() -> Self {
|
||||||
|
# Self {}
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
#
|
||||||
|
# pub struct Query;
|
||||||
|
#
|
||||||
|
# #[graphql_object(context = Database)]
|
||||||
|
# impl Query {
|
||||||
|
# fn hello_world() -> &'static str {
|
||||||
|
# "Hello World!"
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
#
|
||||||
|
# pub struct Subscription;
|
||||||
|
#
|
||||||
|
# type StringStream = Pin<Box<dyn Stream<Item = Result<String, FieldError>> + Send>>;
|
||||||
|
#
|
||||||
|
# #[graphql_subscription(context = Database)]
|
||||||
|
# impl Subscription {
|
||||||
|
# async fn hello_world() -> StringStream {
|
||||||
|
# let stream =
|
||||||
|
# futures::stream::iter(vec![Ok(String::from("Hello")), Ok(String::from("World!"))]);
|
||||||
|
# Box::pin(stream)
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
type Schema = RootNode<'static, Query, EmptyMutation<Database>, Subscription>;
|
||||||
|
|
||||||
|
fn schema() -> Schema {
|
||||||
|
Schema::new(Query {}, EmptyMutation::new(), Subscription {})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_subscription() {
|
||||||
|
let schema = schema();
|
||||||
|
let coordinator = Coordinator::new(schema);
|
||||||
|
let req: GraphQLRequest<DefaultScalarValue> = serde_json::from_str(
|
||||||
|
r#"{
|
||||||
|
"query": "subscription { helloWorld }"
|
||||||
|
}"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let ctx = Database::new();
|
||||||
|
let mut conn = coordinator.subscribe(&req, &ctx).await.unwrap();
|
||||||
|
while let Some(result) = conn.next().await {
|
||||||
|
println!("{}", serde_json::to_string(&result).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() { }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Web Integration and Examples
|
||||||
|
|
||||||
|
Currently there is an example of subscriptions with [warp][warp], but it still in an alpha state.
|
||||||
|
GraphQL over [WS][WS] is not fully supported yet and is non-standard.
|
||||||
|
|
||||||
|
- [Warp Subscription Example](https://github.com/graphql-rust/juniper/tree/master/examples/warp_subscriptions)
|
||||||
|
- [Small Example](https://github.com/graphql-rust/juniper/tree/master/examples/basic_subscriptions)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
[juniper_subscriptions]: https://github.com/graphql-rust/juniper/tree/master/juniper_subscriptions
|
||||||
|
[Stream]: https://docs.rs/futures/0.3.4/futures/stream/trait.Stream.html
|
||||||
|
<!-- TODO: Fix these links when the documentation for the `juniper_subscriptions` are defined in the docs. --->
|
||||||
|
[Coordinator]: https://docs.rs/juniper_subscriptions/0.15.0/struct.Coordinator.html
|
||||||
|
[SubscriptionCoordinator]: https://docs.rs/juniper_subscriptions/0.15.0/trait.SubscriptionCoordinator.html
|
||||||
|
[Connection]: https://docs.rs/juniper_subscriptions/0.15.0/struct.Connection.html
|
||||||
|
[SubscriptionConnection]: https://docs.rs/juniper_subscriptions/0.15.0/trait.SubscriptionConnection.html
|
||||||
|
<!--- --->
|
||||||
|
[Future]: https://docs.rs/futures/0.3.4/futures/future/trait.Future.html
|
||||||
|
[warp]: https://github.com/graphql-rust/juniper/tree/master/juniper_warp
|
||||||
|
[WS]: https://github.com/apollographql/subscriptions-transport-ws/blob/master/PROTOCOL.md
|
||||||
|
[GraphQLError]: https://docs.rs/juniper/0.14.2/juniper/enum.GraphQLError.html
|
||||||
|
[Schema]: ../schema/schemas_and_mutations.md
|
210
docs/book/content/quickstart.md
Normal file
210
docs/book/content/quickstart.md
Normal file
|
@ -0,0 +1,210 @@
|
||||||
|
# Quickstart
|
||||||
|
|
||||||
|
This page will give you a short introduction to the concepts in Juniper.
|
||||||
|
|
||||||
|
Juniper follows a [code-first approach][schema_approach] to defining GraphQL schemas. If you would like to use a [schema-first approach][schema_approach] instead, consider [juniper-from-schema][] for generating code from a schema file.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
juniper = "0.15"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Schema example
|
||||||
|
|
||||||
|
Exposing simple enums and structs as GraphQL is just a matter of adding a custom
|
||||||
|
derive attribute to them. Juniper includes support for basic Rust types that
|
||||||
|
naturally map to GraphQL features, such as `Option<T>`, `Vec<T>`, `Box<T>`,
|
||||||
|
`String`, `f64`, and `i32`, references, and slices.
|
||||||
|
|
||||||
|
For more advanced mappings, Juniper provides multiple macros to map your Rust
|
||||||
|
types to a GraphQL schema. The most important one is the
|
||||||
|
[graphql_object][graphql_object] procedural macro that is used for declaring an object with
|
||||||
|
resolvers, which you will use for the `Query` and `Mutation` roots.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(unused_variables)]
|
||||||
|
# extern crate juniper;
|
||||||
|
# use std::fmt::Display;
|
||||||
|
use juniper::{
|
||||||
|
graphql_object, EmptySubscription, FieldResult, GraphQLEnum,
|
||||||
|
GraphQLInputObject, GraphQLObject, ScalarValue,
|
||||||
|
};
|
||||||
|
#
|
||||||
|
# struct DatabasePool;
|
||||||
|
# impl DatabasePool {
|
||||||
|
# fn get_connection(&self) -> FieldResult<DatabasePool> { Ok(DatabasePool) }
|
||||||
|
# fn find_human(&self, _id: &str) -> FieldResult<Human> { Err("")? }
|
||||||
|
# fn insert_human(&self, _human: &NewHuman) -> FieldResult<Human> { Err("")? }
|
||||||
|
# }
|
||||||
|
|
||||||
|
#[derive(GraphQLEnum)]
|
||||||
|
enum Episode {
|
||||||
|
NewHope,
|
||||||
|
Empire,
|
||||||
|
Jedi,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(description = "A humanoid creature in the Star Wars universe")]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
name: String,
|
||||||
|
appears_in: Vec<Episode>,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
// There is also a custom derive for mapping GraphQL input objects.
|
||||||
|
|
||||||
|
#[derive(GraphQLInputObject)]
|
||||||
|
#[graphql(description = "A humanoid creature in the Star Wars universe")]
|
||||||
|
struct NewHuman {
|
||||||
|
name: String,
|
||||||
|
appears_in: Vec<Episode>,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now, we create our root Query and Mutation types with resolvers by using the
|
||||||
|
// object macro.
|
||||||
|
// Objects can have contexts that allow accessing shared state like a database
|
||||||
|
// pool.
|
||||||
|
|
||||||
|
struct Context {
|
||||||
|
// Use your real database pool here.
|
||||||
|
pool: DatabasePool,
|
||||||
|
}
|
||||||
|
|
||||||
|
// To make our context usable by Juniper, we have to implement a marker trait.
|
||||||
|
impl juniper::Context for Context {}
|
||||||
|
|
||||||
|
struct Query;
|
||||||
|
|
||||||
|
#[graphql_object(
|
||||||
|
// Here we specify the context type for the object.
|
||||||
|
// We need to do this in every type that
|
||||||
|
// needs access to the context.
|
||||||
|
context = Context,
|
||||||
|
)]
|
||||||
|
impl Query {
|
||||||
|
fn apiVersion() -> &'static str {
|
||||||
|
"1.0"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Arguments to resolvers can either be simple types or input objects.
|
||||||
|
// To gain access to the context, we specify a argument
|
||||||
|
// that is a reference to the Context type.
|
||||||
|
// Juniper automatically injects the correct context here.
|
||||||
|
fn human(context: &Context, id: String) -> FieldResult<Human> {
|
||||||
|
// Get a db connection.
|
||||||
|
let connection = context.pool.get_connection()?;
|
||||||
|
// Execute a db query.
|
||||||
|
// Note the use of `?` to propagate errors.
|
||||||
|
let human = connection.find_human(&id)?;
|
||||||
|
// Return the result.
|
||||||
|
Ok(human)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now, we do the same for our Mutation type.
|
||||||
|
|
||||||
|
struct Mutation;
|
||||||
|
|
||||||
|
#[graphql_object(
|
||||||
|
context = Context,
|
||||||
|
// If we need to use `ScalarValue` parametrization explicitly somewhere
|
||||||
|
// in the object definition (like here in `FieldResult`), we could
|
||||||
|
// declare an explicit type parameter for that, and specify it.
|
||||||
|
scalar = S: ScalarValue + Display,
|
||||||
|
)]
|
||||||
|
impl Mutation {
|
||||||
|
fn createHuman<S: ScalarValue + Display>(context: &Context, new_human: NewHuman) -> FieldResult<Human, S> {
|
||||||
|
let db = context.pool.get_connection().map_err(|e| e.map_scalar_value())?;
|
||||||
|
let human: Human = db.insert_human(&new_human).map_err(|e| e.map_scalar_value())?;
|
||||||
|
Ok(human)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A root schema consists of a query, a mutation, and a subscription.
|
||||||
|
// Request queries can be executed against a RootNode.
|
||||||
|
type Schema = juniper::RootNode<'static, Query, Mutation, EmptySubscription<Context>>;
|
||||||
|
#
|
||||||
|
# fn main() {
|
||||||
|
# let _ = Schema::new(Query, Mutation{}, EmptySubscription::new());
|
||||||
|
# }
|
||||||
|
```
|
||||||
|
|
||||||
|
We now have a very simple but functional schema for a GraphQL server!
|
||||||
|
|
||||||
|
To actually serve the schema, see the guides for our various [server integrations](./servers/index.md).
|
||||||
|
|
||||||
|
Juniper is a library that can be used in many contexts--it does not require a server and it does not have a dependency on a particular transport or serialization format. You can invoke the executor directly to get a result for a query:
|
||||||
|
|
||||||
|
## Executor
|
||||||
|
|
||||||
|
You can invoke `juniper::execute` directly to run a GraphQL query:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# // Only needed due to 2018 edition because the macro is not accessible.
|
||||||
|
# #[macro_use] extern crate juniper;
|
||||||
|
use juniper::{
|
||||||
|
graphql_object, EmptyMutation, EmptySubscription, FieldResult,
|
||||||
|
GraphQLEnum, Variables, graphql_value,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(GraphQLEnum, Clone, Copy)]
|
||||||
|
enum Episode {
|
||||||
|
NewHope,
|
||||||
|
Empire,
|
||||||
|
Jedi,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Arbitrary context data.
|
||||||
|
struct Ctx(Episode);
|
||||||
|
|
||||||
|
impl juniper::Context for Ctx {}
|
||||||
|
|
||||||
|
struct Query;
|
||||||
|
|
||||||
|
#[graphql_object(context = Ctx)]
|
||||||
|
impl Query {
|
||||||
|
fn favoriteEpisode(context: &Ctx) -> FieldResult<Episode> {
|
||||||
|
Ok(context.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A root schema consists of a query, a mutation, and a subscription.
|
||||||
|
// Request queries can be executed against a RootNode.
|
||||||
|
type Schema = juniper::RootNode<'static, Query, EmptyMutation<Ctx>, EmptySubscription<Ctx>>;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// Create a context object.
|
||||||
|
let ctx = Ctx(Episode::NewHope);
|
||||||
|
|
||||||
|
// Run the executor.
|
||||||
|
let (res, _errors) = juniper::execute_sync(
|
||||||
|
"query { favoriteEpisode }",
|
||||||
|
None,
|
||||||
|
&Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()),
|
||||||
|
&Variables::new(),
|
||||||
|
&ctx,
|
||||||
|
).unwrap();
|
||||||
|
|
||||||
|
// Ensure the value matches.
|
||||||
|
assert_eq!(
|
||||||
|
res,
|
||||||
|
graphql_value!({
|
||||||
|
"favoriteEpisode": "NEW_HOPE",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
[juniper-from-schema]: https://github.com/davidpdrsn/juniper-from-schema
|
||||||
|
[schema_approach]: https://blog.logrocket.com/code-first-vs-schema-first-development-graphql/
|
||||||
|
[hyper]: servers/hyper.md
|
||||||
|
[warp]: servers/warp.md
|
||||||
|
[rocket]: servers/rocket.md
|
||||||
|
[iron]: servers/iron.md
|
||||||
|
[tutorial]: ./tutorial.html
|
||||||
|
[graphql_object]: https://docs.rs/juniper/latest/juniper/macro.graphql_object.html
|
118
docs/book/content/schema/schemas_and_mutations.md
Normal file
118
docs/book/content/schema/schemas_and_mutations.md
Normal file
|
@ -0,0 +1,118 @@
|
||||||
|
# Schemas
|
||||||
|
|
||||||
|
Juniper follows a [code-first approach][schema_approach] to defining GraphQL schemas. If you would like to use a [schema-first approach][schema_approach] instead, consider [juniper-from-schema][] for generating code from a schema file.
|
||||||
|
|
||||||
|
A schema consists of three types: a query object, a mutation object, and a subscription object.
|
||||||
|
These three define the root query fields, mutations and subscriptions of the schema, respectively.
|
||||||
|
|
||||||
|
The usage of subscriptions is a little different from the mutation and query objects, so there is a specific [section][section] that discusses them.
|
||||||
|
|
||||||
|
Both query and mutation objects are regular GraphQL objects, defined like any
|
||||||
|
other object in Juniper. The mutation and subscription objects, however, are optional since schemas
|
||||||
|
can be read-only and do not require subscriptions. If mutation/subscription functionality is not needed, consider using [EmptyMutation][EmptyMutation]/[EmptySubscription][EmptySubscription].
|
||||||
|
|
||||||
|
In Juniper, the `RootNode` type represents a schema. When the schema is first created,
|
||||||
|
Juniper will traverse the entire object graph
|
||||||
|
and register all types it can find. This means that if you define a GraphQL
|
||||||
|
object somewhere but never reference it, it will not be exposed in a schema.
|
||||||
|
|
||||||
|
## The query root
|
||||||
|
|
||||||
|
The query root is just a GraphQL object. You define it like any other GraphQL
|
||||||
|
object in Juniper, most commonly using the `graphql_object` proc macro:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(unused_variables)]
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::{graphql_object, FieldResult, GraphQLObject};
|
||||||
|
# #[derive(GraphQLObject)] struct User { name: String }
|
||||||
|
struct Root;
|
||||||
|
|
||||||
|
#[graphql_object]
|
||||||
|
impl Root {
|
||||||
|
fn userWithUsername(username: String) -> FieldResult<Option<User>> {
|
||||||
|
// Look up user in database...
|
||||||
|
# unimplemented!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() { }
|
||||||
|
```
|
||||||
|
|
||||||
|
## Mutations
|
||||||
|
|
||||||
|
Mutations are _also_ just GraphQL objects. Each mutation is a single field
|
||||||
|
that performs some mutating side-effect such as updating a database.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(unused_variables)]
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::{graphql_object, FieldResult, GraphQLObject};
|
||||||
|
# #[derive(GraphQLObject)] struct User { name: String }
|
||||||
|
struct Mutations;
|
||||||
|
|
||||||
|
#[graphql_object]
|
||||||
|
impl Mutations {
|
||||||
|
fn signUpUser(name: String, email: String) -> FieldResult<User> {
|
||||||
|
// Validate inputs and save user in database...
|
||||||
|
# unimplemented!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() { }
|
||||||
|
```
|
||||||
|
|
||||||
|
# Converting a Rust schema to the [GraphQL Schema Language][schema_language]
|
||||||
|
|
||||||
|
Many tools in the GraphQL ecosystem require the schema to be defined in the [GraphQL Schema Language][schema_language]. You can generate a [GraphQL Schema Language][schema_language] representation of your schema defined in Rust using the `schema-language` feature (on by default):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::{
|
||||||
|
graphql_object, EmptyMutation, EmptySubscription, FieldResult, RootNode,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Query;
|
||||||
|
|
||||||
|
#[graphql_object]
|
||||||
|
impl Query {
|
||||||
|
fn hello(&self) -> FieldResult<&str> {
|
||||||
|
Ok("hello world")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// Define our schema in Rust.
|
||||||
|
let schema = RootNode::new(
|
||||||
|
Query,
|
||||||
|
EmptyMutation::<()>::new(),
|
||||||
|
EmptySubscription::<()>::new(),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Convert the Rust schema into the GraphQL Schema Language.
|
||||||
|
let result = schema.as_schema_language();
|
||||||
|
|
||||||
|
let expected = "\
|
||||||
|
type Query {
|
||||||
|
hello: String!
|
||||||
|
}
|
||||||
|
|
||||||
|
schema {
|
||||||
|
query: Query
|
||||||
|
}
|
||||||
|
";
|
||||||
|
assert_eq!(result, expected);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Note the `schema-language` feature may be turned off if you do not need this functionality to reduce dependencies and speed up
|
||||||
|
compile times.
|
||||||
|
|
||||||
|
|
||||||
|
[schema_language]: https://graphql.org/learn/schema/#type-language
|
||||||
|
[juniper-from-schema]: https://github.com/davidpdrsn/juniper-from-schema
|
||||||
|
[schema_approach]: https://blog.logrocket.com/code-first-vs-schema-first-development-graphql/
|
||||||
|
[section]: ../advanced/subscriptions.md
|
||||||
|
[EmptyMutation]: https://docs.rs/juniper/0.14.2/juniper/struct.EmptyMutation.html
|
||||||
|
<!--TODO: Fix This URL when the EmptySubscription become available in the Documentation -->
|
||||||
|
[EmptySubscription]: https://docs.rs/juniper/0.14.2/juniper/struct.EmptySubscription.html
|
28
docs/book/content/servers/hyper.md
Normal file
28
docs/book/content/servers/hyper.md
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
# Integrating with Hyper
|
||||||
|
|
||||||
|
[Hyper] is a fast HTTP implementation that many other Rust web frameworks
|
||||||
|
leverage. It offers asynchronous I/O via the tokio runtime and works on
|
||||||
|
Rust's stable channel.
|
||||||
|
|
||||||
|
Hyper is not a higher-level web framework and accordingly
|
||||||
|
does not include ergonomic features such as simple endpoint routing,
|
||||||
|
baked-in HTTP responses, or reusable middleware. For GraphQL, those aren't
|
||||||
|
large downsides as all POSTs and GETs usually go through a single endpoint with
|
||||||
|
a few clearly-defined response payloads.
|
||||||
|
|
||||||
|
Juniper's Hyper integration is contained in the [`juniper_hyper`][juniper_hyper] crate:
|
||||||
|
|
||||||
|
!FILENAME Cargo.toml
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
juniper = "0.10"
|
||||||
|
juniper_hyper = "0.1.0"
|
||||||
|
```
|
||||||
|
|
||||||
|
Included in the source is a [small example][example] which sets up a basic GraphQL and [GraphiQL] handler.
|
||||||
|
|
||||||
|
[graphiql]: https://github.com/graphql/graphiql
|
||||||
|
[hyper]: https://hyper.rs/
|
||||||
|
[juniper_hyper]: https://github.com/graphql-rust/juniper/tree/master/juniper_hyper
|
||||||
|
[example]: https://github.com/graphql-rust/juniper/blob/master/juniper_hyper/examples/hyper_server.rs
|
17
docs/book/content/servers/index.md
Normal file
17
docs/book/content/servers/index.md
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
# Adding A Server
|
||||||
|
|
||||||
|
To allow using Juniper with the HTTP server of your choice,
|
||||||
|
it does **not** come with a built in HTTP server.
|
||||||
|
|
||||||
|
To actually get a server up and running, there are multiple official and
|
||||||
|
third-party integration crates that will get you there.
|
||||||
|
|
||||||
|
- [Official Server Integrations](official.md)
|
||||||
|
- [Warp](warp.md)
|
||||||
|
- [Rocket](rocket.md)
|
||||||
|
- [Iron](iron.md)
|
||||||
|
- [Hyper](hyper.md)
|
||||||
|
- [Third Party Integrations](third-party.md)
|
||||||
|
- [Actix-Web](https://github.com/actix/examples/tree/master/juniper)
|
||||||
|
- [Finchers](https://github.com/finchers-rs/finchers-juniper)
|
||||||
|
- [Tsukuyomi](https://github.com/tsukuyomi-rs/tsukuyomi/tree/master/examples/juniper)
|
122
docs/book/content/servers/iron.md
Normal file
122
docs/book/content/servers/iron.md
Normal file
|
@ -0,0 +1,122 @@
|
||||||
|
# Integrating with Iron
|
||||||
|
|
||||||
|
[Iron] is a library that's been around for a while in the Rust sphere but lately
|
||||||
|
hasn't seen much of development. Nevertheless, it's still a solid library with a
|
||||||
|
familiar request/response/middleware architecture that works on Rust's stable
|
||||||
|
channel.
|
||||||
|
|
||||||
|
Juniper's Iron integration is contained in the `juniper_iron` crate:
|
||||||
|
|
||||||
|
!FILENAME Cargo.toml
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
juniper = "0.10"
|
||||||
|
juniper_iron = "0.2.0"
|
||||||
|
```
|
||||||
|
|
||||||
|
Included in the source is a [small
|
||||||
|
example](https://github.com/graphql-rust/juniper_iron/blob/master/examples/iron_server.rs)
|
||||||
|
which sets up a basic GraphQL and [GraphiQL] handler.
|
||||||
|
|
||||||
|
## Basic integration
|
||||||
|
|
||||||
|
Let's start with a minimal schema and just get a GraphQL endpoint up and
|
||||||
|
running. We use [mount] to attach the GraphQL handler at `/graphql`.
|
||||||
|
|
||||||
|
The `context_factory` function will be executed on every request and can be used
|
||||||
|
to set up database connections, read session token information from cookies, and
|
||||||
|
set up other global data that the schema might require.
|
||||||
|
|
||||||
|
In this example, we won't use any global data so we just return an empty value.
|
||||||
|
|
||||||
|
```rust,ignore
|
||||||
|
extern crate juniper;
|
||||||
|
extern crate juniper_iron;
|
||||||
|
extern crate iron;
|
||||||
|
extern crate mount;
|
||||||
|
|
||||||
|
use mount::Mount;
|
||||||
|
use iron::prelude::*;
|
||||||
|
use juniper::EmptyMutation;
|
||||||
|
use juniper_iron::GraphQLHandler;
|
||||||
|
|
||||||
|
fn context_factory(_: &mut Request) -> IronResult<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Root;
|
||||||
|
|
||||||
|
#[juniper::graphql_object]
|
||||||
|
impl Root {
|
||||||
|
fn foo() -> String {
|
||||||
|
"Bar".to_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# #[allow(unreachable_code, unused_variables)]
|
||||||
|
fn main() {
|
||||||
|
let mut mount = Mount::new();
|
||||||
|
|
||||||
|
let graphql_endpoint = GraphQLHandler::new(
|
||||||
|
context_factory,
|
||||||
|
Root,
|
||||||
|
EmptyMutation::<()>::new(),
|
||||||
|
);
|
||||||
|
|
||||||
|
mount.mount("/graphql", graphql_endpoint);
|
||||||
|
|
||||||
|
let chain = Chain::new(mount);
|
||||||
|
|
||||||
|
# return;
|
||||||
|
Iron::new(chain).http("0.0.0.0:8080").unwrap();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Accessing data from the request
|
||||||
|
|
||||||
|
If you want to access e.g. the source IP address of the request from a field
|
||||||
|
resolver, you need to pass this data using Juniper's [context feature](../types/objects/using_contexts.md).
|
||||||
|
|
||||||
|
```rust,ignore
|
||||||
|
# extern crate juniper;
|
||||||
|
# extern crate juniper_iron;
|
||||||
|
# extern crate iron;
|
||||||
|
# use iron::prelude::*;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
struct Context {
|
||||||
|
remote_addr: SocketAddr,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl juniper::Context for Context {}
|
||||||
|
|
||||||
|
fn context_factory(req: &mut Request) -> IronResult<Context> {
|
||||||
|
Ok(Context {
|
||||||
|
remote_addr: req.remote_addr
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Root;
|
||||||
|
|
||||||
|
#[juniper::graphql_object(
|
||||||
|
Context = Context,
|
||||||
|
)]
|
||||||
|
impl Root {
|
||||||
|
field my_addr(context: &Context) -> String {
|
||||||
|
format!("Hello, you're coming from {}", context.remote_addr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# fn main() {
|
||||||
|
# let _graphql_endpoint = juniper_iron::GraphQLHandler::new(
|
||||||
|
# context_factory,
|
||||||
|
# Root,
|
||||||
|
# juniper::EmptyMutation::<Context>::new(),
|
||||||
|
# );
|
||||||
|
# }
|
||||||
|
```
|
||||||
|
|
||||||
|
[iron]: https://github.com/iron/iron
|
||||||
|
[graphiql]: https://github.com/graphql/graphiql
|
||||||
|
[mount]: https://github.com/iron/mount
|
9
docs/book/content/servers/official.md
Normal file
9
docs/book/content/servers/official.md
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
# Official Server Integrations
|
||||||
|
|
||||||
|
Juniper provides official integration crates for several popular Rust server
|
||||||
|
libraries.
|
||||||
|
|
||||||
|
- [Warp](warp.md)
|
||||||
|
- [Rocket](rocket.md)
|
||||||
|
- [Iron](iron.md)
|
||||||
|
- [Hyper](hyper.md)
|
22
docs/book/content/servers/rocket.md
Normal file
22
docs/book/content/servers/rocket.md
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
# Integrating with Rocket
|
||||||
|
|
||||||
|
[Rocket] is a web framework for Rust that makes it simple to write fast web applications without sacrificing flexibility or type safety. All with minimal code. Rocket
|
||||||
|
does not work on Rust's stable channel and instead requires the nightly
|
||||||
|
channel.
|
||||||
|
|
||||||
|
Juniper's Rocket integration is contained in the [`juniper_rocket`][juniper_rocket] crate:
|
||||||
|
|
||||||
|
!FILENAME Cargo.toml
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
juniper = "0.10"
|
||||||
|
juniper_rocket = "0.2.0"
|
||||||
|
```
|
||||||
|
|
||||||
|
Included in the source is a [small example][example] which sets up a basic GraphQL and [GraphiQL] handler.
|
||||||
|
|
||||||
|
[graphiql]: https://github.com/graphql/graphiql
|
||||||
|
[rocket]: https://rocket.rs/
|
||||||
|
[juniper_rocket]: https://github.com/graphql-rust/juniper/tree/master/juniper_rocket
|
||||||
|
[example]: https://github.com/graphql-rust/juniper/blob/master/juniper_rocket/examples/rocket_server.rs
|
5
docs/book/content/servers/third-party.md
Normal file
5
docs/book/content/servers/third-party.md
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
# Other Examples
|
||||||
|
|
||||||
|
These examples are not officially maintained by Juniper developers.
|
||||||
|
|
||||||
|
- [Actix Web](https://github.com/actix/examples/tree/HEAD/graphql/juniper) | [Actix Web (advanced)](https://github.com/actix/examples/tree/HEAD/graphql/juniper-advanced)
|
23
docs/book/content/servers/warp.md
Normal file
23
docs/book/content/servers/warp.md
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
# Integrating with Warp
|
||||||
|
|
||||||
|
[Warp] is a super-easy, composable, web server framework for warp speeds.
|
||||||
|
The fundamental building block of warp is the Filter: they can be combined and composed to express rich requirements on requests. Warp is built on [Hyper] and works on
|
||||||
|
Rust's stable channel.
|
||||||
|
|
||||||
|
Juniper's Warp integration is contained in the [`juniper_warp`][juniper_warp] crate:
|
||||||
|
|
||||||
|
!FILENAME Cargo.toml
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
juniper = "0.10"
|
||||||
|
juniper_warp = "0.1.0"
|
||||||
|
```
|
||||||
|
|
||||||
|
Included in the source is a [small example][example] which sets up a basic GraphQL and [GraphiQL] handler.
|
||||||
|
|
||||||
|
[graphiql]: https://github.com/graphql/graphiql
|
||||||
|
[hyper]: https://hyper.rs/
|
||||||
|
[warp]: https://crates.io/crates/warp
|
||||||
|
[juniper_warp]: https://github.com/graphql-rust/juniper/tree/master/juniper_warp
|
||||||
|
[example]: https://github.com/graphql-rust/juniper/blob/master/juniper_warp/examples/warp_server.rs
|
73
docs/book/content/types/enums.md
Normal file
73
docs/book/content/types/enums.md
Normal file
|
@ -0,0 +1,73 @@
|
||||||
|
# Enums
|
||||||
|
|
||||||
|
Enums in GraphQL are string constants grouped together to represent a set of
|
||||||
|
possible values. Simple Rust enums can be converted to GraphQL enums by using a
|
||||||
|
custom derive attribute:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
#[derive(juniper::GraphQLEnum)]
|
||||||
|
enum Episode {
|
||||||
|
NewHope,
|
||||||
|
Empire,
|
||||||
|
Jedi,
|
||||||
|
}
|
||||||
|
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
Juniper converts all enum variants to uppercase, so the corresponding string
|
||||||
|
values for these variants are `NEWHOPE`, `EMPIRE`, and `JEDI`, respectively. If
|
||||||
|
you want to override this, you can use the `graphql` attribute, similar to how
|
||||||
|
it works when [defining objects](objects/defining_objects.md):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
#[derive(juniper::GraphQLEnum)]
|
||||||
|
enum Episode {
|
||||||
|
#[graphql(name="NEW_HOPE")]
|
||||||
|
NewHope,
|
||||||
|
Empire,
|
||||||
|
Jedi,
|
||||||
|
}
|
||||||
|
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Documentation and deprecation
|
||||||
|
|
||||||
|
Just like when defining objects, the type itself can be renamed and documented,
|
||||||
|
while individual enum variants can be renamed, documented, and deprecated:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
#[derive(juniper::GraphQLEnum)]
|
||||||
|
#[graphql(name="Episode", description="An episode of Star Wars")]
|
||||||
|
enum StarWarsEpisode {
|
||||||
|
#[graphql(deprecated="We don't really talk about this one")]
|
||||||
|
ThePhantomMenace,
|
||||||
|
|
||||||
|
#[graphql(name="NEW_HOPE")]
|
||||||
|
NewHope,
|
||||||
|
|
||||||
|
#[graphql(description="Arguably the best one in the trilogy")]
|
||||||
|
Empire,
|
||||||
|
Jedi,
|
||||||
|
}
|
||||||
|
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Supported Macro Attributes (Derive)
|
||||||
|
|
||||||
|
| Name of Attribute | Container Support | Field Support |
|
||||||
|
|-------------------|:-----------------:|:----------------:|
|
||||||
|
| context | ✔ | ? |
|
||||||
|
| deprecated | ✔ | ✔ |
|
||||||
|
| description | ✔ | ✔ |
|
||||||
|
| interfaces | ? | ✘ |
|
||||||
|
| name | ✔ | ✔ |
|
||||||
|
| noasync | ✔ | ? |
|
||||||
|
| scalar | ✘ | ? |
|
||||||
|
| skip | ? | ✘ |
|
||||||
|
| ✔: supported | ✘: not supported | ?: not available |
|
20
docs/book/content/types/index.md
Normal file
20
docs/book/content/types/index.md
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
# Type System
|
||||||
|
|
||||||
|
Most of the work in working with juniper consists of mapping the
|
||||||
|
GraphQL type system to the Rust types your application uses.
|
||||||
|
|
||||||
|
Juniper provides some convenient abstractions that try to make this process
|
||||||
|
as painless as possible.
|
||||||
|
|
||||||
|
Find out more in the individual chapters below.
|
||||||
|
|
||||||
|
- [Defining objects](objects/defining_objects.md)
|
||||||
|
- [Complex fields](objects/complex_fields.md)
|
||||||
|
- [Using contexts](objects/using_contexts.md)
|
||||||
|
- [Error handling](objects/error_handling.md)
|
||||||
|
- [Other types](other-index.md)
|
||||||
|
- [Enums](enums.md)
|
||||||
|
- [Interfaces](interfaces.md)
|
||||||
|
- [Input objects](input_objects.md)
|
||||||
|
- [Scalars](scalars.md)
|
||||||
|
- [Unions](unions.md)
|
62
docs/book/content/types/input_objects.md
Normal file
62
docs/book/content/types/input_objects.md
Normal file
|
@ -0,0 +1,62 @@
|
||||||
|
# Input objects
|
||||||
|
|
||||||
|
Input objects are complex data structures that can be used as arguments to
|
||||||
|
GraphQL fields. In Juniper, you can define input objects using a custom derive
|
||||||
|
attribute, similar to simple objects and enums:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(unused_variables)]
|
||||||
|
# extern crate juniper;
|
||||||
|
#[derive(juniper::GraphQLInputObject)]
|
||||||
|
struct Coordinate {
|
||||||
|
latitude: f64,
|
||||||
|
longitude: f64
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Root;
|
||||||
|
# #[derive(juniper::GraphQLObject)] struct User { name: String }
|
||||||
|
|
||||||
|
#[juniper::graphql_object]
|
||||||
|
impl Root {
|
||||||
|
fn users_at_location(coordinate: Coordinate, radius: f64) -> Vec<User> {
|
||||||
|
// Send coordinate to database
|
||||||
|
// ...
|
||||||
|
# unimplemented!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Documentation and renaming
|
||||||
|
|
||||||
|
Just like the [other](objects/defining_objects.md) [derives](enums.md), you can rename
|
||||||
|
and add documentation to both the type and the fields:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(unused_variables)]
|
||||||
|
# extern crate juniper;
|
||||||
|
#[derive(juniper::GraphQLInputObject)]
|
||||||
|
#[graphql(name="Coordinate", description="A position on the globe")]
|
||||||
|
struct WorldCoordinate {
|
||||||
|
#[graphql(name="lat", description="The latitude")]
|
||||||
|
latitude: f64,
|
||||||
|
|
||||||
|
#[graphql(name="long", description="The longitude")]
|
||||||
|
longitude: f64
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Root;
|
||||||
|
# #[derive(juniper::GraphQLObject)] struct User { name: String }
|
||||||
|
|
||||||
|
#[juniper::graphql_object]
|
||||||
|
impl Root {
|
||||||
|
fn users_at_location(coordinate: WorldCoordinate, radius: f64) -> Vec<User> {
|
||||||
|
// Send coordinate to database
|
||||||
|
// ...
|
||||||
|
# unimplemented!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# fn main() {}
|
||||||
|
```
|
480
docs/book/content/types/interfaces.md
Normal file
480
docs/book/content/types/interfaces.md
Normal file
|
@ -0,0 +1,480 @@
|
||||||
|
Interfaces
|
||||||
|
==========
|
||||||
|
|
||||||
|
[GraphQL interfaces][1] map well to interfaces known from common object-oriented languages such as Java or C#, but Rust, unfortunately, has no concept that maps perfectly to them. The nearest analogue of [GraphQL interfaces][1] are Rust traits, and the main difference is that in GraphQL an [interface type][1] serves both as an _abstraction_ and a _boxed value (downcastable to concrete implementers)_, while in Rust, a trait is an _abstraction only_ and _to represent such a boxed value a separate type is required_, like enum or trait object, because Rust trait doesn't represent a type itself, and so can have no values. This difference imposes some unintuitive and non-obvious corner cases when we try to express [GraphQL interfaces][1] in Rust, but on the other hand gives you full control over which type is backing your interface, and how it's resolved.
|
||||||
|
|
||||||
|
For implementing [GraphQL interfaces][1] Juniper provides the `#[graphql_interface]` macro.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Traits
|
||||||
|
|
||||||
|
Defining a trait is mandatory for defining a [GraphQL interface][1], because this is the _obvious_ way we describe an _abstraction_ in Rust. All [interface][1] fields are defined as computed ones via trait methods.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::graphql_interface;
|
||||||
|
|
||||||
|
#[graphql_interface]
|
||||||
|
trait Character {
|
||||||
|
fn id(&self) -> &str;
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
However, to return values of such [interface][1], we should provide its implementers and the Rust type representing a _boxed value of this trait_. The last one can be represented in two flavors: enum and [trait object][2].
|
||||||
|
|
||||||
|
|
||||||
|
### Enum values (default)
|
||||||
|
|
||||||
|
By default, Juniper generates an enum representing the values of the defined [GraphQL interface][1], and names it straightforwardly, `{Interface}Value`.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::{graphql_interface, GraphQLObject};
|
||||||
|
|
||||||
|
#[graphql_interface(for = [Human, Droid])] // enumerating all implementers is mandatory
|
||||||
|
trait Character {
|
||||||
|
fn id(&self) -> &str;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(impl = CharacterValue)] // notice enum name, NOT trait name
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
#[graphql_interface] // implementing requires macro attribute too, (°o°)!
|
||||||
|
impl Character for Human {
|
||||||
|
fn id(&self) -> &str {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(impl = CharacterValue)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
#[graphql_interface]
|
||||||
|
impl Character for Droid {
|
||||||
|
fn id(&self) -> &str {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# fn main() {
|
||||||
|
let human = Human { id: "human-32".to_owned() };
|
||||||
|
// Values type for interface has `From` implementations for all its implementers,
|
||||||
|
// so we don't need to bother with enum variant names.
|
||||||
|
let character: CharacterValue = human.into();
|
||||||
|
assert_eq!(character.id(), "human-32");
|
||||||
|
# }
|
||||||
|
```
|
||||||
|
|
||||||
|
Also, enum name can be specified explicitly, if desired.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::{graphql_interface, GraphQLObject};
|
||||||
|
|
||||||
|
#[graphql_interface(enum = CharaterInterface, for = Human)]
|
||||||
|
trait Character {
|
||||||
|
fn id(&self) -> &str;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(impl = CharaterInterface)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
#[graphql_interface]
|
||||||
|
impl Character for Human {
|
||||||
|
fn id(&self) -> &str {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Trait object values
|
||||||
|
|
||||||
|
If, for some reason, we would like to use [trait objects][2] for representing [interface][1] values incorporating dynamic dispatch, then it should be specified explicitly in the trait definition.
|
||||||
|
|
||||||
|
Downcasting [trait objects][2] in Rust is not that trivial, that's why macro transforms the trait definition slightly, imposing some additional type parameters under-the-hood.
|
||||||
|
|
||||||
|
> __NOTICE__:
|
||||||
|
> A __trait has to be [object safe](https://doc.rust-lang.org/stable/reference/items/traits.html#object-safety)__, because schema resolvers will need to return a [trait object][2] to specify a [GraphQL interface][1] behind it.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# extern crate tokio;
|
||||||
|
use juniper::{graphql_interface, GraphQLObject};
|
||||||
|
|
||||||
|
// `dyn` argument accepts the name of type alias for the required trait object,
|
||||||
|
// and macro generates this alias automatically.
|
||||||
|
#[graphql_interface(dyn = DynCharacter, for = Human)]
|
||||||
|
trait Character {
|
||||||
|
async fn id(&self) -> &str; // async fields are supported natively
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(impl = DynCharacter<__S>)] // macro adds `ScalarValue` type parameter to trait,
|
||||||
|
struct Human { // so it may be specified explicitly when required
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
#[graphql_interface(dyn)] // implementing requires to know about dynamic dispatch too
|
||||||
|
impl Character for Human {
|
||||||
|
async fn id(&self) -> &str {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(impl = DynCharacter<__S>)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
#[graphql_interface]
|
||||||
|
impl Character for Droid {
|
||||||
|
async fn id(&self) -> &str {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# #[tokio::main]
|
||||||
|
# async fn main() {
|
||||||
|
let human = Human { id: "human-32".to_owned() };
|
||||||
|
let character: Box<DynCharacter> = Box::new(human);
|
||||||
|
assert_eq!(character.id().await, "human-32");
|
||||||
|
# }
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Ignoring trait methods
|
||||||
|
|
||||||
|
We may want to omit some trait methods to be assumed as [GraphQL interface][1] fields and ignore them.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::{graphql_interface, GraphQLObject};
|
||||||
|
|
||||||
|
#[graphql_interface(for = Human)]
|
||||||
|
trait Character {
|
||||||
|
fn id(&self) -> &str;
|
||||||
|
|
||||||
|
#[graphql(ignore)] // or `#[graphql(skip)]`, your choice
|
||||||
|
fn ignored(&self) -> u32 { 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(impl = CharacterValue)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
#[graphql_interface]
|
||||||
|
impl Character for Human {
|
||||||
|
fn id(&self) -> &str {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Fields, arguments and interface customization
|
||||||
|
|
||||||
|
Similarly to [GraphQL objects][5] Juniper allows to fully customize [interface][1] fields and their arguments.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(deprecated)]
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::graphql_interface;
|
||||||
|
|
||||||
|
// Renames the interface in GraphQL schema.
|
||||||
|
#[graphql_interface(name = "MyCharacter")]
|
||||||
|
// Describes the interface in GraphQL schema.
|
||||||
|
#[graphql_interface(description = "My own character.")]
|
||||||
|
// Usual Rust docs are supported too as GraphQL interface description,
|
||||||
|
// but `description` attribute argument takes precedence over them, if specified.
|
||||||
|
/// This doc is absent in GraphQL schema.
|
||||||
|
trait Character {
|
||||||
|
// Renames the field in GraphQL schema.
|
||||||
|
#[graphql(name = "myId")]
|
||||||
|
// Deprecates the field in GraphQL schema.
|
||||||
|
// Usual Rust `#[deprecated]` attribute is supported too as field deprecation,
|
||||||
|
// but `deprecated` attribute argument takes precedence over it, if specified.
|
||||||
|
#[graphql(deprecated = "Do not use it.")]
|
||||||
|
// Describes the field in GraphQL schema.
|
||||||
|
#[graphql(description = "ID of my own character.")]
|
||||||
|
// Usual Rust docs are supported too as field description,
|
||||||
|
// but `description` attribute argument takes precedence over them, if specified.
|
||||||
|
/// This description is absent in GraphQL schema.
|
||||||
|
fn id(
|
||||||
|
&self,
|
||||||
|
// Renames the argument in GraphQL schema.
|
||||||
|
#[graphql(name = "myNum")]
|
||||||
|
// Describes the argument in GraphQL schema.
|
||||||
|
#[graphql(description = "ID number of my own character.")]
|
||||||
|
// Specifies the default value for the argument.
|
||||||
|
// The concrete value may be omitted, and the `Default::default` one
|
||||||
|
// will be used in such case.
|
||||||
|
#[graphql(default = 5)]
|
||||||
|
num: i32,
|
||||||
|
) -> &str;
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
Renaming policies for all [GraphQL interface][1] fields and arguments are supported as well:
|
||||||
|
```rust
|
||||||
|
# #![allow(deprecated)]
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::graphql_interface;
|
||||||
|
|
||||||
|
#[graphql_interface(rename_all = "none")] // disables any renaming
|
||||||
|
trait Character {
|
||||||
|
// Now exposed as `my_id` and `my_num` in the schema
|
||||||
|
fn my_id(&self, my_num: i32) -> &str;
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Custom context
|
||||||
|
|
||||||
|
If a [`Context`][6] is required in a trait method to resolve a [GraphQL interface][1] field, specify it as an argument.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use std::collections::HashMap;
|
||||||
|
use juniper::{graphql_interface, GraphQLObject};
|
||||||
|
|
||||||
|
struct Database {
|
||||||
|
humans: HashMap<String, Human>,
|
||||||
|
}
|
||||||
|
impl juniper::Context for Database {}
|
||||||
|
|
||||||
|
#[graphql_interface(for = Human)] // look, ma, context type is inferred! \(^o^)/
|
||||||
|
trait Character { // while still can be specified via `Context = ...` attribute argument
|
||||||
|
// If a field argument is named `context` or `ctx`, it's automatically assumed
|
||||||
|
// as a context argument.
|
||||||
|
fn id(&self, context: &Database) -> Option<&str>;
|
||||||
|
|
||||||
|
// Otherwise, you may mark it explicitly as a context argument.
|
||||||
|
fn name(&self, #[graphql(context)] db: &Database) -> Option<&str>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(impl = CharacterValue, Context = Database)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
#[graphql_interface]
|
||||||
|
impl Character for Human {
|
||||||
|
fn id(&self, db: &Database) -> Option<&str> {
|
||||||
|
if db.humans.contains_key(&self.id) {
|
||||||
|
Some(&self.id)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name(&self, db: &Database) -> Option<&str> {
|
||||||
|
if db.humans.contains_key(&self.id) {
|
||||||
|
Some(&self.name)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Using executor and explicit generic scalar
|
||||||
|
|
||||||
|
If an [`Executor`][4] is required in a trait method to resolve a [GraphQL interface][1] field, specify it as an argument.
|
||||||
|
|
||||||
|
This requires to explicitly parametrize over [`ScalarValue`][3], as [`Executor`][4] does so.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::{graphql_interface, Executor, GraphQLObject, LookAheadMethods as _, ScalarValue};
|
||||||
|
|
||||||
|
#[graphql_interface(for = Human, Scalar = S)] // notice specifying `ScalarValue` as existing type parameter
|
||||||
|
trait Character<S: ScalarValue> {
|
||||||
|
// If a field argument is named `executor`, it's automatically assumed
|
||||||
|
// as an executor argument.
|
||||||
|
async fn id<'a>(&self, executor: &'a Executor<'_, '_, (), S>) -> &'a str
|
||||||
|
where
|
||||||
|
S: Send + Sync; // required by `#[async_trait]` transformation ¯\_(ツ)_/¯
|
||||||
|
|
||||||
|
// Otherwise, you may mark it explicitly as an executor argument.
|
||||||
|
async fn name<'b>(
|
||||||
|
&'b self,
|
||||||
|
#[graphql(executor)] another: &Executor<'_, '_, (), S>,
|
||||||
|
) -> &'b str
|
||||||
|
where
|
||||||
|
S: Send + Sync;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(impl = CharacterValue<__S>)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
#[graphql_interface(scalar = S)]
|
||||||
|
impl<S: ScalarValue> Character<S> for Human {
|
||||||
|
async fn id<'a>(&self, executor: &'a Executor<'_, '_, (), S>) -> &'a str
|
||||||
|
where
|
||||||
|
S: Send + Sync,
|
||||||
|
{
|
||||||
|
executor.look_ahead().field_name()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn name<'b>(&'b self, _: &Executor<'_, '_, (), S>) -> &'b str
|
||||||
|
where
|
||||||
|
S: Send + Sync,
|
||||||
|
{
|
||||||
|
&self.name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Downcasting
|
||||||
|
|
||||||
|
By default, the [GraphQL interface][1] value is downcast to one of its implementer types via matching the enum variant or downcasting the trait object (if `dyn` macro argument is used).
|
||||||
|
|
||||||
|
However, if some custom logic is needed to downcast a [GraphQL interface][1] implementer, you may specify either an external function or a trait method to do so.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use std::collections::HashMap;
|
||||||
|
use juniper::{graphql_interface, GraphQLObject};
|
||||||
|
|
||||||
|
struct Database {
|
||||||
|
droids: HashMap<String, Droid>,
|
||||||
|
}
|
||||||
|
impl juniper::Context for Database {}
|
||||||
|
|
||||||
|
#[graphql_interface(for = [Human, Droid], context = Database)]
|
||||||
|
#[graphql_interface(on Droid = get_droid)] // enables downcasting `Droid` via `get_droid()` function
|
||||||
|
trait Character {
|
||||||
|
fn id(&self) -> &str;
|
||||||
|
|
||||||
|
#[graphql(downcast)] // makes method a downcast to `Human`, not a field
|
||||||
|
// NOTICE: The method signature may optionally contain `&Database` context argument.
|
||||||
|
fn as_human(&self) -> Option<&Human> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(impl = CharacterValue, Context = Database)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
#[graphql_interface]
|
||||||
|
impl Character for Human {
|
||||||
|
fn id(&self) -> &str {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn as_human(&self) -> Option<&Self> {
|
||||||
|
Some(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(impl = CharacterValue, Context = Database)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
#[graphql_interface]
|
||||||
|
impl Character for Droid {
|
||||||
|
fn id(&self) -> &str {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// External downcast function doesn't have to be a method of a type.
|
||||||
|
// It's only a matter of the function signature to match the requirements.
|
||||||
|
fn get_droid<'db>(ch: &CharacterValue, db: &'db Database) -> Option<&'db Droid> {
|
||||||
|
db.droids.get(ch.id())
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
The attribute syntax `#[graphql_interface(on ImplementerType = resolver_fn)]` follows the [GraphQL syntax for downcasting interface implementer](https://spec.graphql.org/June2018/#example-5cc55).
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## `ScalarValue` considerations
|
||||||
|
|
||||||
|
By default, `#[graphql_interface]` macro generates code, which is generic over a [`ScalarValue`][3] type. This may introduce a problem when at least one of [GraphQL interface][1] implementers is restricted to a concrete [`ScalarValue`][3] type in its implementation. To resolve such problem, a concrete [`ScalarValue`][3] type should be specified.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::{graphql_interface, DefaultScalarValue, GraphQLObject};
|
||||||
|
|
||||||
|
#[graphql_interface(for = [Human, Droid])]
|
||||||
|
#[graphql_interface(scalar = DefaultScalarValue)] // removing this line will fail compilation
|
||||||
|
trait Character {
|
||||||
|
fn id(&self) -> &str;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(impl = CharacterValue, Scalar = DefaultScalarValue)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
#[graphql_interface(scalar = DefaultScalarValue)]
|
||||||
|
impl Character for Human {
|
||||||
|
fn id(&self) -> &str {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(impl = CharacterValue, Scalar = DefaultScalarValue)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
primary_function: String,
|
||||||
|
}
|
||||||
|
#[graphql_interface(scalar = DefaultScalarValue)]
|
||||||
|
impl Character for Droid {
|
||||||
|
fn id(&self) -> &str {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
[1]: https://spec.graphql.org/June2018/#sec-Interfaces
|
||||||
|
[2]: https://doc.rust-lang.org/reference/types/trait-object.html
|
||||||
|
[3]: https://docs.rs/juniper/latest/juniper/trait.ScalarValue.html
|
||||||
|
[4]: https://docs.rs/juniper/latest/juniper/struct.Executor.html
|
||||||
|
[5]: https://spec.graphql.org/June2018/#sec-Objects
|
||||||
|
[6]: https://docs.rs/juniper/0.14.2/juniper/trait.Context.html
|
206
docs/book/content/types/objects/complex_fields.md
Normal file
206
docs/book/content/types/objects/complex_fields.md
Normal file
|
@ -0,0 +1,206 @@
|
||||||
|
# Complex fields
|
||||||
|
|
||||||
|
If you've got a struct that can't be mapped directly to GraphQL, that contains
|
||||||
|
computed fields or circular structures, you have to use a more powerful tool:
|
||||||
|
the `#[graphql_object]` procedural macro. This macro lets you define GraphQL object
|
||||||
|
fields in a Rust `impl` block for a type. Note, that GraphQL fields are defined in
|
||||||
|
this `impl` block by default. If you want to define normal methods on the struct,
|
||||||
|
you have to do so either in a separate "normal" `impl` block, or mark them with
|
||||||
|
`#[graphql(ignore)]` attribute to be omitted by the macro. Continuing with the
|
||||||
|
example from the last chapter, this is how you would define `Person` using the
|
||||||
|
macro:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(dead_code)]
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::graphql_object;
|
||||||
|
#
|
||||||
|
struct Person {
|
||||||
|
name: String,
|
||||||
|
age: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[graphql_object]
|
||||||
|
impl Person {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
self.name.as_str()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn age(&self) -> i32 {
|
||||||
|
self.age
|
||||||
|
}
|
||||||
|
|
||||||
|
#[graphql(ignore)]
|
||||||
|
pub fn hidden_from_graphql(&self) {
|
||||||
|
// [...]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Person {
|
||||||
|
pub fn hidden_from_graphql2(&self) {
|
||||||
|
// [...]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() { }
|
||||||
|
```
|
||||||
|
|
||||||
|
While this is a bit more verbose, it lets you write any kind of function in the
|
||||||
|
field resolver. With this syntax, fields can also take arguments:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::{graphql_object, GraphQLObject};
|
||||||
|
#
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Person {
|
||||||
|
name: String,
|
||||||
|
age: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct House {
|
||||||
|
inhabitants: Vec<Person>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[graphql_object]
|
||||||
|
impl House {
|
||||||
|
// Creates the field `inhabitantWithName(name)`, returning a nullable `Person`.
|
||||||
|
fn inhabitant_with_name(&self, name: String) -> Option<&Person> {
|
||||||
|
self.inhabitants.iter().find(|p| p.name == name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
To access global data such as database connections or authentication
|
||||||
|
information, a _context_ is used. To learn more about this, see the next
|
||||||
|
chapter: [Using contexts](using_contexts.md).
|
||||||
|
|
||||||
|
## Description, renaming, and deprecation
|
||||||
|
|
||||||
|
Like with the derive attribute, field names will be converted from `snake_case`
|
||||||
|
to `camelCase`. If you need to override the conversion, you can simply rename
|
||||||
|
the field. Also, the type name can be changed with an alias:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::graphql_object;
|
||||||
|
#
|
||||||
|
struct Person;
|
||||||
|
|
||||||
|
/// Doc comments are used as descriptions for GraphQL.
|
||||||
|
#[graphql_object(
|
||||||
|
// With this attribute you can change the public GraphQL name of the type.
|
||||||
|
name = "PersonObject",
|
||||||
|
|
||||||
|
// You can also specify a description here, which will overwrite
|
||||||
|
// a doc comment description.
|
||||||
|
description = "...",
|
||||||
|
)]
|
||||||
|
impl Person {
|
||||||
|
/// A doc comment on the field will also be used for GraphQL.
|
||||||
|
#[graphql(
|
||||||
|
// Or provide a description here.
|
||||||
|
description = "...",
|
||||||
|
)]
|
||||||
|
fn doc_comment(&self) -> &str {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fields can also be renamed if required.
|
||||||
|
#[graphql(name = "myCustomFieldName")]
|
||||||
|
fn renamed_field() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecations also work as you'd expect.
|
||||||
|
// Both the standard Rust syntax and a custom attribute is accepted.
|
||||||
|
#[deprecated(note = "...")]
|
||||||
|
fn deprecated_standard() -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
#[graphql(deprecated = "...")]
|
||||||
|
fn deprecated_graphql() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() { }
|
||||||
|
```
|
||||||
|
|
||||||
|
Or provide a different renaming policy on a `impl` block for all its fields:
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::graphql_object;
|
||||||
|
struct Person;
|
||||||
|
|
||||||
|
#[graphql_object(rename_all = "none")] // disables any renaming
|
||||||
|
impl Person {
|
||||||
|
// Now exposed as `renamed_field` in the schema
|
||||||
|
fn renamed_field() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Customizing arguments
|
||||||
|
|
||||||
|
Method field arguments can also be customized.
|
||||||
|
|
||||||
|
They can have custom descriptions and default values.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::graphql_object;
|
||||||
|
#
|
||||||
|
struct Person {}
|
||||||
|
|
||||||
|
#[graphql_object]
|
||||||
|
impl Person {
|
||||||
|
fn field1(
|
||||||
|
&self,
|
||||||
|
#[graphql(
|
||||||
|
// Arguments can also be renamed if required.
|
||||||
|
name = "arg",
|
||||||
|
// Set a default value which will be injected if not present.
|
||||||
|
// The default can be any valid Rust expression, including a function call, etc.
|
||||||
|
default = true,
|
||||||
|
// Set a description.
|
||||||
|
description = "The first argument..."
|
||||||
|
)]
|
||||||
|
arg1: bool,
|
||||||
|
// If default expression is not specified then `Default::default()` value is used.
|
||||||
|
#[graphql(default)]
|
||||||
|
arg2: i32,
|
||||||
|
) -> String {
|
||||||
|
format!("{} {}", arg1, arg2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() { }
|
||||||
|
```
|
||||||
|
|
||||||
|
Provide a different renaming policy on a `impl` block also implies for arguments:
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::graphql_object;
|
||||||
|
struct Person;
|
||||||
|
|
||||||
|
#[graphql_object(rename_all = "none")] // disables any renaming
|
||||||
|
impl Person {
|
||||||
|
// Now exposed as `my_arg` in the schema
|
||||||
|
fn field(my_arg: bool) -> bool {
|
||||||
|
my_arg
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
## More features
|
||||||
|
|
||||||
|
These, and more features, are described more thoroughly in [the reference documentation](https://docs.rs/juniper/latest/juniper/attr.graphql_object.html).
|
216
docs/book/content/types/objects/defining_objects.md
Normal file
216
docs/book/content/types/objects/defining_objects.md
Normal file
|
@ -0,0 +1,216 @@
|
||||||
|
# Defining objects
|
||||||
|
|
||||||
|
While any type in Rust can be exposed as a GraphQL object, the most common one
|
||||||
|
is a struct.
|
||||||
|
|
||||||
|
There are two ways to create a GraphQL object in Juniper. If you've got a simple
|
||||||
|
struct you want to expose, the easiest way is to use the custom derive
|
||||||
|
attribute. The other way is described in the [Complex fields](complex_fields.md)
|
||||||
|
chapter.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::GraphQLObject;
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Person {
|
||||||
|
name: String,
|
||||||
|
age: i32,
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
This will create a GraphQL object type called `Person`, with two fields: `name`
|
||||||
|
of type `String!`, and `age` of type `Int!`. Because of Rust's type system,
|
||||||
|
everything is exported as non-null by default. If you need a nullable field, you
|
||||||
|
can use `Option<T>`.
|
||||||
|
|
||||||
|
We should take advantage of the
|
||||||
|
fact that GraphQL is self-documenting and add descriptions to the type and
|
||||||
|
fields. Juniper will automatically use associated doc comments as GraphQL
|
||||||
|
descriptions:
|
||||||
|
|
||||||
|
!FILENAME GraphQL descriptions via Rust doc comments
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::GraphQLObject;
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
/// Information about a person
|
||||||
|
struct Person {
|
||||||
|
/// The person's full name, including both first and last names
|
||||||
|
name: String,
|
||||||
|
/// The person's age in years, rounded down
|
||||||
|
age: i32,
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
Objects and fields without doc comments can instead set a `description`
|
||||||
|
via the `graphql` attribute. The following example is equivalent to the above:
|
||||||
|
|
||||||
|
!FILENAME GraphQL descriptions via attribute
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::GraphQLObject;
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(description = "Information about a person")]
|
||||||
|
struct Person {
|
||||||
|
#[graphql(description = "The person's full name, including both first and last names")]
|
||||||
|
name: String,
|
||||||
|
#[graphql(description = "The person's age in years, rounded down")]
|
||||||
|
age: i32,
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
Descriptions set via the `graphql` attribute take precedence over Rust
|
||||||
|
doc comments. This enables internal Rust documentation and external GraphQL
|
||||||
|
documentation to differ:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::GraphQLObject;
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(description = "This description shows up in GraphQL")]
|
||||||
|
/// This description shows up in RustDoc
|
||||||
|
struct Person {
|
||||||
|
#[graphql(description = "This description shows up in GraphQL")]
|
||||||
|
/// This description shows up in RustDoc
|
||||||
|
name: String,
|
||||||
|
/// This description shows up in both RustDoc and GraphQL
|
||||||
|
age: i32,
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Relationships
|
||||||
|
|
||||||
|
You can only use the custom derive attribute under these circumstances:
|
||||||
|
|
||||||
|
- The annotated type is a `struct`,
|
||||||
|
- Every struct field is either
|
||||||
|
- A primitive type (`i32`, `f64`, `bool`, `String`, `juniper::ID`), or
|
||||||
|
- A valid custom GraphQL type, e.g. another struct marked with this attribute,
|
||||||
|
or
|
||||||
|
- A container/reference containing any of the above, e.g. `Vec<T>`, `Box<T>`,
|
||||||
|
`Option<T>`
|
||||||
|
|
||||||
|
Let's see what that means for building relationships between objects:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::GraphQLObject;
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Person {
|
||||||
|
name: String,
|
||||||
|
age: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct House {
|
||||||
|
address: Option<String>, // Converted into String (nullable)
|
||||||
|
inhabitants: Vec<Person>, // Converted into [Person!]!
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
Because `Person` is a valid GraphQL type, you can have a `Vec<Person>` in a
|
||||||
|
struct and it'll be automatically converted into a list of non-nullable `Person`
|
||||||
|
objects.
|
||||||
|
|
||||||
|
## Renaming fields
|
||||||
|
|
||||||
|
By default, struct fields are converted from Rust's standard `snake_case` naming
|
||||||
|
convention into GraphQL's `camelCase` convention:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::GraphQLObject;
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Person {
|
||||||
|
first_name: String, // Would be exposed as firstName in the GraphQL schema
|
||||||
|
last_name: String, // Exposed as lastName
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
You can override the name by using the `graphql` attribute on individual struct
|
||||||
|
fields:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::GraphQLObject;
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Person {
|
||||||
|
name: String,
|
||||||
|
age: i32,
|
||||||
|
#[graphql(name = "websiteURL")]
|
||||||
|
website_url: Option<String>, // now exposed as `websiteURL` in the schema
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
Or provide a different renaming policy on a struct for all its fields:
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::GraphQLObject;
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(rename_all = "none")] // disables any renaming
|
||||||
|
struct Person {
|
||||||
|
name: String,
|
||||||
|
age: i32,
|
||||||
|
website_url: Option<String>, // now exposed as `website_url` in the schema
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deprecating fields
|
||||||
|
|
||||||
|
To deprecate a field, you specify a deprecation reason using the `graphql`
|
||||||
|
attribute:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::GraphQLObject;
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Person {
|
||||||
|
name: String,
|
||||||
|
age: i32,
|
||||||
|
#[graphql(deprecated = "Please use the name field instead")]
|
||||||
|
first_name: String,
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `name`, `description`, and `deprecation` arguments can of course be
|
||||||
|
combined. Some restrictions from the GraphQL spec still applies though; you can
|
||||||
|
only deprecate object fields and enum values.
|
||||||
|
|
||||||
|
## Ignoring fields
|
||||||
|
|
||||||
|
By default, all fields in a `GraphQLObject` are included in the generated GraphQL type. To prevent including a specific field, annotate the field with `#[graphql(ignore)]`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::GraphQLObject;
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Person {
|
||||||
|
name: String,
|
||||||
|
age: i32,
|
||||||
|
#[graphql(ignore)]
|
||||||
|
# #[allow(dead_code)]
|
||||||
|
password_hash: String, // cannot be queried or modified from GraphQL
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
467
docs/book/content/types/objects/error_handling.md
Normal file
467
docs/book/content/types/objects/error_handling.md
Normal file
|
@ -0,0 +1,467 @@
|
||||||
|
# Error handling
|
||||||
|
|
||||||
|
Error handling in GraphQL can be done in multiple ways. In the
|
||||||
|
following two different error handling models are discussed: field
|
||||||
|
results and GraphQL schema backed errors. Each approach has its
|
||||||
|
advantages. Choosing the right error handling method depends on the
|
||||||
|
requirements of the application--investigating both approaches is
|
||||||
|
beneficial.
|
||||||
|
|
||||||
|
## Field Results
|
||||||
|
|
||||||
|
Rust
|
||||||
|
[provides](https://doc.rust-lang.org/book/second-edition/ch09-00-error-handling.html)
|
||||||
|
two ways of dealing with errors: `Result<T, E>` for recoverable errors and
|
||||||
|
`panic!` for unrecoverable errors. Juniper does not do anything about panicking;
|
||||||
|
it will bubble up to the surrounding framework and hopefully be dealt with
|
||||||
|
there.
|
||||||
|
|
||||||
|
For recoverable errors, Juniper works well with the built-in `Result` type, you
|
||||||
|
can use the `?` operator and things will generally just work as you expect them to:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
use std::{
|
||||||
|
str,
|
||||||
|
path::PathBuf,
|
||||||
|
fs::{File},
|
||||||
|
io::{Read},
|
||||||
|
};
|
||||||
|
use juniper::{graphql_object, FieldResult};
|
||||||
|
|
||||||
|
struct Example {
|
||||||
|
filename: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[graphql_object]
|
||||||
|
impl Example {
|
||||||
|
fn contents(&self) -> FieldResult<String> {
|
||||||
|
let mut file = File::open(&self.filename)?;
|
||||||
|
let mut contents = String::new();
|
||||||
|
file.read_to_string(&mut contents)?;
|
||||||
|
Ok(contents)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn foo() -> FieldResult<Option<String>> {
|
||||||
|
// Some invalid bytes.
|
||||||
|
let invalid = vec![128, 223];
|
||||||
|
|
||||||
|
Ok(Some(str::from_utf8(&invalid)?.to_string()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
`FieldResult<T>` is an alias for `Result<T, FieldError>`, which is the error
|
||||||
|
type all fields must return. By using the `?` operator or `try!` macro, any type
|
||||||
|
that implements the `Display` trait - which are most of the error types out
|
||||||
|
there - those errors are automatically converted into `FieldError`.
|
||||||
|
|
||||||
|
## Error payloads, `null`, and partial errors
|
||||||
|
|
||||||
|
Juniper's error behavior conforms to the [GraphQL specification](https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability).
|
||||||
|
|
||||||
|
When a field returns an error, the field's result is replaced by `null`, an
|
||||||
|
additional `errors` object is created at the top level of the response, and the
|
||||||
|
execution is resumed. For example, with the previous example and the following
|
||||||
|
query:
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
{
|
||||||
|
example {
|
||||||
|
contents
|
||||||
|
foo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If `str::from_utf8` resulted in a `std::str::Utf8Error`, the following would be
|
||||||
|
returned:
|
||||||
|
|
||||||
|
!FILENAME Response for nullable field with error
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"example": {
|
||||||
|
contents: "<Contents of the file>",
|
||||||
|
foo: null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"errors": [
|
||||||
|
"message": "invalid utf-8 sequence of 2 bytes from index 0",
|
||||||
|
"locations": [{ "line": 2, "column": 4 }])
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If an error is returned from a non-null field, such as the
|
||||||
|
example above, the `null` value is propagated up to the first nullable parent
|
||||||
|
field, or the root `data` object if there are no nullable fields.
|
||||||
|
|
||||||
|
For example, with the following query:
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
{
|
||||||
|
example {
|
||||||
|
contents
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If `File::open()` above resulted in `std::io::ErrorKind::PermissionDenied`, the
|
||||||
|
following would be returned:
|
||||||
|
|
||||||
|
!FILENAME Response for non-null field with error and no nullable parent
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"errors": [
|
||||||
|
"message": "Permission denied (os error 13)",
|
||||||
|
"locations": [{ "line": 2, "column": 4 }])
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Structured errors
|
||||||
|
|
||||||
|
Sometimes it is desirable to return additional structured error information
|
||||||
|
to clients. This can be accomplished by implementing [`IntoFieldError`](https://docs.rs/juniper/latest/juniper/trait.IntoFieldError.html):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #[macro_use] extern crate juniper;
|
||||||
|
# use juniper::{graphql_object, FieldError, IntoFieldError, ScalarValue};
|
||||||
|
#
|
||||||
|
enum CustomError {
|
||||||
|
WhateverNotSet,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S: ScalarValue> IntoFieldError<S> for CustomError {
|
||||||
|
fn into_field_error(self) -> FieldError<S> {
|
||||||
|
match self {
|
||||||
|
CustomError::WhateverNotSet => FieldError::new(
|
||||||
|
"Whatever does not exist",
|
||||||
|
graphql_value!({
|
||||||
|
"type": "NO_WHATEVER"
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Example {
|
||||||
|
whatever: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[graphql_object]
|
||||||
|
impl Example {
|
||||||
|
fn whatever(&self) -> Result<bool, CustomError> {
|
||||||
|
if let Some(value) = self.whatever {
|
||||||
|
return Ok(value);
|
||||||
|
}
|
||||||
|
Err(CustomError::WhateverNotSet)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
The specified structured error information is included in the [`extensions`](https://facebook.github.io/graphql/June2018/#sec-Errors) key:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"errors": [{
|
||||||
|
"message": "Whatever does not exist",
|
||||||
|
"locations": [{"line": 2, "column": 4}],
|
||||||
|
"extensions": {
|
||||||
|
"type": "NO_WHATEVER"
|
||||||
|
}
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Errors Backed by GraphQL's Schema
|
||||||
|
|
||||||
|
Rust's model of errors can be adapted for GraphQL. Rust's panic is
|
||||||
|
similar to a `FieldError`--the whole query is aborted and nothing can
|
||||||
|
be extracted (except for error related information).
|
||||||
|
|
||||||
|
Not all errors require this strict handling. Recoverable or partial errors can be put
|
||||||
|
into the GraphQL schema so the client can intelligently handle them.
|
||||||
|
|
||||||
|
To implement this approach, all errors must be partitioned into two error classes:
|
||||||
|
|
||||||
|
* Critical errors that cannot be fixed by the user (e.g. a database error).
|
||||||
|
* Recoverable errors that can be fixed by the user (e.g. invalid input data).
|
||||||
|
|
||||||
|
Critical errors are returned from resolvers as `FieldErrors` (from the previous section). Non-critical errors are part of the GraphQL schema and can be handled gracefully by clients. Similar to Rust, GraphQL allows similar error models with unions (see Unions).
|
||||||
|
|
||||||
|
### Example Input Validation (simple)
|
||||||
|
|
||||||
|
In this example, basic input validation is implemented with GraphQL
|
||||||
|
types. Strings are used to identify the problematic field name. Errors
|
||||||
|
for a particular field are also returned as a string. In this example
|
||||||
|
the string contains a server-side localized error message. However, it is also
|
||||||
|
possible to return a unique string identifier and have the client present a localized string to the user.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::{graphql_object, GraphQLObject, GraphQLUnion};
|
||||||
|
#
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
pub struct Item {
|
||||||
|
name: String,
|
||||||
|
quantity: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
pub struct ValidationError {
|
||||||
|
field: String,
|
||||||
|
message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
pub struct ValidationErrors {
|
||||||
|
errors: Vec<ValidationError>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLUnion)]
|
||||||
|
pub enum GraphQLResult {
|
||||||
|
Ok(Item),
|
||||||
|
Err(ValidationErrors),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Mutation;
|
||||||
|
|
||||||
|
#[graphql_object]
|
||||||
|
impl Mutation {
|
||||||
|
fn addItem(&self, name: String, quantity: i32) -> GraphQLResult {
|
||||||
|
let mut errors = Vec::new();
|
||||||
|
|
||||||
|
if !(10 <= name.len() && name.len() <= 100) {
|
||||||
|
errors.push(ValidationError {
|
||||||
|
field: "name".to_string(),
|
||||||
|
message: "between 10 and 100".to_string()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if !(1 <= quantity && quantity <= 10) {
|
||||||
|
errors.push(ValidationError {
|
||||||
|
field: "quantity".to_string(),
|
||||||
|
message: "between 1 and 10".to_string()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if errors.is_empty() {
|
||||||
|
GraphQLResult::Ok(Item { name, quantity })
|
||||||
|
} else {
|
||||||
|
GraphQLResult::Err(ValidationErrors { errors })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
Each function may have a different return type and depending on the input
|
||||||
|
parameters a new result type is required. For example, adding a user
|
||||||
|
requires a new result type which contains the variant `Ok(User)`
|
||||||
|
instead of `Ok(Item)`.
|
||||||
|
|
||||||
|
The client can send a mutation request and handle the
|
||||||
|
resulting errors as shown in the following example:
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
{
|
||||||
|
mutation {
|
||||||
|
addItem(name: "", quantity: 0) {
|
||||||
|
... on Item {
|
||||||
|
name
|
||||||
|
}
|
||||||
|
... on ValidationErrors {
|
||||||
|
errors {
|
||||||
|
field
|
||||||
|
message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
A useful side effect of this approach is to have partially successful
|
||||||
|
queries or mutations. If one resolver fails, the results of the
|
||||||
|
successful resolvers are not discarded.
|
||||||
|
|
||||||
|
### Example Input Validation (complex)
|
||||||
|
|
||||||
|
Instead of using strings to propagate errors, it is possible to use
|
||||||
|
GraphQL's type system to describe the errors more precisely.
|
||||||
|
|
||||||
|
For each fallible input variable a field in a GraphQL object is created. The
|
||||||
|
field is set if the validation for that particular field fails. You will likely want some kind of code generation to reduce repetition as the number of types required is significantly larger than
|
||||||
|
before. Each resolver function has a custom `ValidationResult` which
|
||||||
|
contains only fields provided by the function.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use juniper::{graphql_object, GraphQLObject, GraphQLUnion};
|
||||||
|
#
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
pub struct Item {
|
||||||
|
name: String,
|
||||||
|
quantity: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
pub struct ValidationError {
|
||||||
|
name: Option<String>,
|
||||||
|
quantity: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLUnion)]
|
||||||
|
pub enum GraphQLResult {
|
||||||
|
Ok(Item),
|
||||||
|
Err(ValidationError),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Mutation;
|
||||||
|
|
||||||
|
#[graphql_object]
|
||||||
|
impl Mutation {
|
||||||
|
fn addItem(&self, name: String, quantity: i32) -> GraphQLResult {
|
||||||
|
let mut error = ValidationError {
|
||||||
|
name: None,
|
||||||
|
quantity: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
if !(10 <= name.len() && name.len() <= 100) {
|
||||||
|
error.name = Some("between 10 and 100".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
if !(1 <= quantity && quantity <= 10) {
|
||||||
|
error.quantity = Some("between 1 and 10".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
if error.name.is_none() && error.quantity.is_none() {
|
||||||
|
GraphQLResult::Ok(Item { name, quantity })
|
||||||
|
} else {
|
||||||
|
GraphQLResult::Err(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
{
|
||||||
|
mutation {
|
||||||
|
addItem {
|
||||||
|
... on Item {
|
||||||
|
name
|
||||||
|
}
|
||||||
|
... on ValidationErrorsItem {
|
||||||
|
name
|
||||||
|
quantity
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected errors are handled directly inside the query. Additionally, all
|
||||||
|
non-critical errors are known in advance by both the server and the client.
|
||||||
|
|
||||||
|
### Example Input Validation (complex with critical error)
|
||||||
|
|
||||||
|
Our examples so far have only included non-critical errors. Providing
|
||||||
|
errors inside the GraphQL schema still allows you to return unexpected critical
|
||||||
|
errors when they occur.
|
||||||
|
|
||||||
|
In the following example, a theoretical database could fail
|
||||||
|
and would generate errors. Since it is not common for the database to
|
||||||
|
fail, the corresponding error is returned as a critical error:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
#
|
||||||
|
use juniper::{graphql_object, graphql_value, FieldError, GraphQLObject, GraphQLUnion, ScalarValue};
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
pub struct Item {
|
||||||
|
name: String,
|
||||||
|
quantity: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
pub struct ValidationErrorItem {
|
||||||
|
name: Option<String>,
|
||||||
|
quantity: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLUnion)]
|
||||||
|
pub enum GraphQLResult {
|
||||||
|
Ok(Item),
|
||||||
|
Err(ValidationErrorItem),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum ApiError {
|
||||||
|
Database,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S: ScalarValue> juniper::IntoFieldError<S> for ApiError {
|
||||||
|
fn into_field_error(self) -> FieldError<S> {
|
||||||
|
match self {
|
||||||
|
ApiError::Database => FieldError::new(
|
||||||
|
"Internal database error",
|
||||||
|
graphql_value!({
|
||||||
|
"type": "DATABASE"
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Mutation;
|
||||||
|
|
||||||
|
#[graphql_object]
|
||||||
|
impl Mutation {
|
||||||
|
fn addItem(&self, name: String, quantity: i32) -> Result<GraphQLResult, ApiError> {
|
||||||
|
let mut error = ValidationErrorItem {
|
||||||
|
name: None,
|
||||||
|
quantity: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
if !(10 <= name.len() && name.len() <= 100) {
|
||||||
|
error.name = Some("between 10 and 100".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
if !(1 <= quantity && quantity <= 10) {
|
||||||
|
error.quantity = Some("between 1 and 10".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
if error.name.is_none() && error.quantity.is_none() {
|
||||||
|
Ok(GraphQLResult::Ok(Item { name, quantity }))
|
||||||
|
} else {
|
||||||
|
Ok(GraphQLResult::Err(error))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Additional Material
|
||||||
|
|
||||||
|
The [Shopify API](https://shopify.dev/docs/admin-api/graphql/reference)
|
||||||
|
implements a similar approach. Their API is a good reference to
|
||||||
|
explore this approach in a real world application.
|
||||||
|
|
||||||
|
# Comparison
|
||||||
|
|
||||||
|
The first approach discussed above--where every error is a critical error defined by `FieldResult` --is easier to implement. However, the client does not know what errors may occur and must instead infer what happened from the error string. This is brittle and could change over time due to either the client or server changing. Therefore, extensive integration testing between the client and server is required to maintain the implicit contract between the two.
|
||||||
|
|
||||||
|
Encoding non-critical errors in the GraphQL schema makes the contract between the client and the server explicit. This allows the client to understand and handle these errors correctly and the server to know when changes are potentially breaking clients. However, encoding this error information into the GraphQL schema requires additional code and up-front definition of non-critical errors.
|
150
docs/book/content/types/objects/using_contexts.md
Normal file
150
docs/book/content/types/objects/using_contexts.md
Normal file
|
@ -0,0 +1,150 @@
|
||||||
|
# Using contexts
|
||||||
|
|
||||||
|
The context type is a feature in Juniper that lets field resolvers access global
|
||||||
|
data, most commonly database connections or authentication information. The
|
||||||
|
context is usually created from a _context factory_. How this is defined is
|
||||||
|
specific to the framework integration you're using, so check out the
|
||||||
|
documentation for either the [Iron](../../servers/iron.md) or [Rocket](../../servers/rocket.md)
|
||||||
|
integration.
|
||||||
|
|
||||||
|
In this chapter, we'll show you how to define a context type and use it in field
|
||||||
|
resolvers. Let's say that we have a simple user database in a `HashMap`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(dead_code)]
|
||||||
|
# use std::collections::HashMap;
|
||||||
|
#
|
||||||
|
struct Database {
|
||||||
|
users: HashMap<i32, User>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct User {
|
||||||
|
id: i32,
|
||||||
|
name: String,
|
||||||
|
friend_ids: Vec<i32>,
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() { }
|
||||||
|
```
|
||||||
|
|
||||||
|
We would like a `friends` field on `User` that returns a list of `User` objects.
|
||||||
|
In order to write such a field though, the database must be queried.
|
||||||
|
|
||||||
|
To solve this, we mark the `Database` as a valid context type and assign it to
|
||||||
|
the user object.
|
||||||
|
|
||||||
|
To gain access to the context, we need to specify an argument with the same
|
||||||
|
type as the specified `Context` for the type:
|
||||||
|
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use std::collections::HashMap;
|
||||||
|
# use juniper::graphql_object;
|
||||||
|
#
|
||||||
|
// This struct represents our context.
|
||||||
|
struct Database {
|
||||||
|
users: HashMap<i32, User>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mark the Database as a valid context type for Juniper
|
||||||
|
impl juniper::Context for Database {}
|
||||||
|
|
||||||
|
struct User {
|
||||||
|
id: i32,
|
||||||
|
name: String,
|
||||||
|
friend_ids: Vec<i32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assign Database as the context type for User
|
||||||
|
#[graphql_object(context = Database)]
|
||||||
|
impl User {
|
||||||
|
// Inject the context by specifying an argument with the context type.
|
||||||
|
// Note:
|
||||||
|
// - the type must be a reference
|
||||||
|
// - the name of the argument SHOULD be `context`
|
||||||
|
fn friends<'db>(&self, context: &'db Database) -> Vec<&'db User> {
|
||||||
|
// Use the database to lookup users
|
||||||
|
self.friend_ids.iter()
|
||||||
|
.map(|id| context.users.get(id).expect("Could not find user with ID"))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
self.name.as_str()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn id(&self) -> i32 {
|
||||||
|
self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() { }
|
||||||
|
```
|
||||||
|
|
||||||
|
You only get an immutable reference to the context, so if you want to affect
|
||||||
|
change to the execution, you'll need to use [interior
|
||||||
|
mutability](https://doc.rust-lang.org/book/first-edition/mutability.html#interior-vs-exterior-mutability)
|
||||||
|
using e.g. `RwLock` or `RefCell`.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Dealing with mutable references
|
||||||
|
|
||||||
|
Context cannot be specified by a mutable reference, because concurrent fields resolving may be performed. If you have something in your context that requires access by mutable reference, then you need to leverage the [interior mutability][1] for that.
|
||||||
|
|
||||||
|
For example, when using async runtime with [work stealing][2] (like `tokio`), which obviously requires thread safety in addition, you will need to use a corresponding async version of `RwLock`:
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use std::collections::HashMap;
|
||||||
|
# use juniper::graphql_object;
|
||||||
|
use tokio::sync::RwLock;
|
||||||
|
|
||||||
|
struct Database {
|
||||||
|
requested_count: HashMap<i32, i32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Since we cannot directly implement juniper::Context
|
||||||
|
// for RwLock we use the newtype idiom
|
||||||
|
struct DatabaseContext(RwLock<Database>);
|
||||||
|
|
||||||
|
impl juniper::Context for DatabaseContext {}
|
||||||
|
|
||||||
|
struct User {
|
||||||
|
id: i32,
|
||||||
|
name: String
|
||||||
|
}
|
||||||
|
|
||||||
|
#[graphql_object(context=DatabaseContext)]
|
||||||
|
impl User {
|
||||||
|
async fn times_requested<'db>(&self, context: &'db DatabaseContext) -> i32 {
|
||||||
|
// Acquire a mutable reference and await if async RwLock is used,
|
||||||
|
// which is necessary if context consists async operations like
|
||||||
|
// querying remote databases.
|
||||||
|
// Obtain base type
|
||||||
|
let DatabaseContext(context) = context;
|
||||||
|
// If context is immutable use .read() on RwLock.
|
||||||
|
let mut context = context.write().await;
|
||||||
|
// Preform a mutable operation.
|
||||||
|
context.requested_count.entry(self.id).and_modify(|e| { *e += 1 }).or_insert(1).clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
self.name.as_str()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn id(&self) -> i32 {
|
||||||
|
self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() { }
|
||||||
|
```
|
||||||
|
Replace `tokio::sync::RwLock` with `std::sync::RwLock` (or similar) if you don't intend to use async resolving.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
[1]: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html
|
||||||
|
[2]: https://en.wikipedia.org/wiki/Work_stealing
|
11
docs/book/content/types/other-index.md
Normal file
11
docs/book/content/types/other-index.md
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
# Other Types
|
||||||
|
|
||||||
|
The GraphQL type system provides several types in additon to objects.
|
||||||
|
|
||||||
|
Find out more about each type below:
|
||||||
|
|
||||||
|
- [Enums](enums.md)
|
||||||
|
- [Interfaces](interfaces.md)
|
||||||
|
- [Input objects](input_objects.md)
|
||||||
|
- [Scalars](scalars.md)
|
||||||
|
- [Unions](unions.md)
|
146
docs/book/content/types/scalars.md
Normal file
146
docs/book/content/types/scalars.md
Normal file
|
@ -0,0 +1,146 @@
|
||||||
|
# Scalars
|
||||||
|
|
||||||
|
Scalars are the primitive types at the leaves of a GraphQL query: numbers,
|
||||||
|
strings, and booleans. You can create custom scalars to other primitive values,
|
||||||
|
but this often requires coordination with the client library intended to consume
|
||||||
|
the API you're building.
|
||||||
|
|
||||||
|
Since any value going over the wire is eventually transformed into JSON, you're
|
||||||
|
also limited in the data types you can use.
|
||||||
|
|
||||||
|
There are two ways to define custom scalars.
|
||||||
|
* For simple scalars that just wrap a primitive type, you can use the newtype pattern with
|
||||||
|
a custom derive.
|
||||||
|
* For more advanced use cases with custom validation, you can use
|
||||||
|
the `graphql_scalar` proc macro.
|
||||||
|
|
||||||
|
|
||||||
|
## Built-in scalars
|
||||||
|
|
||||||
|
Juniper has built-in support for:
|
||||||
|
|
||||||
|
* `i32` as `Int`
|
||||||
|
* `f64` as `Float`
|
||||||
|
* `String` and `&str` as `String`
|
||||||
|
* `bool` as `Boolean`
|
||||||
|
* `juniper::ID` as `ID`. This type is defined [in the
|
||||||
|
spec](http://facebook.github.io/graphql/#sec-ID) as a type that is serialized
|
||||||
|
as a string but can be parsed from both a string and an integer.
|
||||||
|
|
||||||
|
Note that there is no built-in support for `i64`/`u64`, as the GraphQL spec [doesn't define any built-in scalars for `i64`/`u64` by default](https://spec.graphql.org/June2018/#sec-Int). You may wish to leverage a [custom GraphQL scalar](#custom-scalars) in your schema to support them.
|
||||||
|
|
||||||
|
**Third party types**:
|
||||||
|
|
||||||
|
Juniper has built-in support for a few additional types from common third party
|
||||||
|
crates. They are enabled via features that are on by default.
|
||||||
|
|
||||||
|
* uuid::Uuid
|
||||||
|
* chrono::DateTime
|
||||||
|
* time::{Date, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset}
|
||||||
|
* url::Url
|
||||||
|
* bson::oid::ObjectId
|
||||||
|
|
||||||
|
## newtype pattern
|
||||||
|
|
||||||
|
Often, you might need a custom scalar that just wraps an existing type.
|
||||||
|
|
||||||
|
This can be done with the newtype pattern and a custom derive, similar to how
|
||||||
|
serde supports this pattern with `#[serde(transparent)]`.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
#[derive(juniper::GraphQLScalarValue)]
|
||||||
|
pub struct UserId(i32);
|
||||||
|
|
||||||
|
#[derive(juniper::GraphQLObject)]
|
||||||
|
struct User {
|
||||||
|
id: UserId,
|
||||||
|
}
|
||||||
|
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
That's it, you can now user `UserId` in your schema.
|
||||||
|
|
||||||
|
The macro also allows for more customization:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
/// You can use a doc comment to specify a description.
|
||||||
|
#[derive(juniper::GraphQLScalarValue)]
|
||||||
|
#[graphql(
|
||||||
|
transparent,
|
||||||
|
// Overwrite the GraphQL type name.
|
||||||
|
name = "MyUserId",
|
||||||
|
// Specify a custom description.
|
||||||
|
// A description in the attribute will overwrite a doc comment.
|
||||||
|
description = "My user id description",
|
||||||
|
)]
|
||||||
|
pub struct UserId(i32);
|
||||||
|
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Custom scalars
|
||||||
|
|
||||||
|
For more complex situations where you also need custom parsing or validation,
|
||||||
|
you can use the `graphql_scalar` proc macro.
|
||||||
|
|
||||||
|
Typically, you represent your custom scalars as strings.
|
||||||
|
|
||||||
|
The example below implements a custom scalar for a custom `Date` type.
|
||||||
|
|
||||||
|
Note: juniper already has built-in support for the `chrono::DateTime` type
|
||||||
|
via `chrono` feature, which is enabled by default and should be used for this
|
||||||
|
purpose.
|
||||||
|
|
||||||
|
The example below is used just for illustration.
|
||||||
|
|
||||||
|
**Note**: the example assumes that the `Date` type implements
|
||||||
|
`std::fmt::Display` and `std::str::FromStr`.
|
||||||
|
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# mod date {
|
||||||
|
# pub struct Date;
|
||||||
|
# impl std::str::FromStr for Date {
|
||||||
|
# type Err = String; fn from_str(_value: &str) -> Result<Self, Self::Err> { unimplemented!() }
|
||||||
|
# }
|
||||||
|
# // And we define how to represent date as a string.
|
||||||
|
# impl std::fmt::Display for Date {
|
||||||
|
# fn fmt(&self, _f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||||
|
# unimplemented!()
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
#
|
||||||
|
use juniper::{Value, ParseScalarResult, ParseScalarValue};
|
||||||
|
use date::Date;
|
||||||
|
|
||||||
|
#[juniper::graphql_scalar(description = "Date")]
|
||||||
|
impl<S> GraphQLScalar for Date
|
||||||
|
where
|
||||||
|
S: ScalarValue
|
||||||
|
{
|
||||||
|
// Define how to convert your custom scalar into a primitive type.
|
||||||
|
fn resolve(&self) -> Value {
|
||||||
|
Value::scalar(self.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Define how to parse a primitive type into your custom scalar.
|
||||||
|
// NOTE: The error type should implement `IntoFieldError<S>`.
|
||||||
|
fn from_input_value(v: &InputValue) -> Result<Date, String> {
|
||||||
|
v.as_string_value()
|
||||||
|
.ok_or_else(|| format!("Expected `String`, found: {}", v))
|
||||||
|
.and_then(|s| s.parse().map_err(|e| format!("Failed to parse `Date`: {}", e)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Define how to parse a string value.
|
||||||
|
fn from_str<'a>(value: ScalarToken<'a>) -> ParseScalarResult<'a, S> {
|
||||||
|
<String as ParseScalarValue<S>>::from_str(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
491
docs/book/content/types/unions.md
Normal file
491
docs/book/content/types/unions.md
Normal file
|
@ -0,0 +1,491 @@
|
||||||
|
Unions
|
||||||
|
======
|
||||||
|
|
||||||
|
From the server's point of view, [GraphQL unions][1] are somewhat similar to [interfaces][5] - the main difference is that they don't contain fields on their own.
|
||||||
|
|
||||||
|
The most obvious and straightforward way to represent a [GraphQL union][1] in Rust is enum. However, we also can do so either with trait or a regular struct. That's why, for implementing [GraphQL unions][1] Juniper provides:
|
||||||
|
- `#[derive(GraphQLUnion)]` macro for enums and structs.
|
||||||
|
- `#[graphql_union]` for traits.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Enums
|
||||||
|
|
||||||
|
Most of the time, we just need a trivial and straightforward Rust enum to represent a [GraphQL union][1].
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# extern crate derive_more;
|
||||||
|
use derive_more::From;
|
||||||
|
use juniper::{GraphQLObject, GraphQLUnion};
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
primary_function: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(From, GraphQLUnion)]
|
||||||
|
enum Character {
|
||||||
|
Human(Human),
|
||||||
|
Droid(Droid),
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Ignoring enum variants
|
||||||
|
|
||||||
|
In some rare situations we may want to omit exposing an enum variant in the GraphQL schema.
|
||||||
|
|
||||||
|
As an example, let's consider the situation where we need to bind some type parameter `T` for doing interesting type-level stuff in our resolvers. To achieve this we need to have `PhantomData<T>`, but we don't want it exposed in the GraphQL schema.
|
||||||
|
|
||||||
|
> __WARNING__:
|
||||||
|
> It's the _library user's responsibility_ to ensure that ignored enum variant is _never_ returned from resolvers, otherwise resolving the GraphQL query will __panic at runtime__.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# extern crate derive_more;
|
||||||
|
# use std::marker::PhantomData;
|
||||||
|
use derive_more::From;
|
||||||
|
use juniper::{GraphQLObject, GraphQLUnion};
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
primary_function: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(From, GraphQLUnion)]
|
||||||
|
enum Character<S> {
|
||||||
|
Human(Human),
|
||||||
|
Droid(Droid),
|
||||||
|
#[from(ignore)]
|
||||||
|
#[graphql(ignore)] // or `#[graphql(skip)]`, your choice
|
||||||
|
_State(PhantomData<S>),
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### External resolver functions
|
||||||
|
|
||||||
|
If some custom logic is needed to resolve a [GraphQL union][1] variant, you may specify an external function to do so:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(dead_code)]
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::{GraphQLObject, GraphQLUnion};
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(Context = CustomContext)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(Context = CustomContext)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
primary_function: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CustomContext {
|
||||||
|
droid: Droid,
|
||||||
|
}
|
||||||
|
impl juniper::Context for CustomContext {}
|
||||||
|
|
||||||
|
#[derive(GraphQLUnion)]
|
||||||
|
#[graphql(Context = CustomContext)]
|
||||||
|
enum Character {
|
||||||
|
Human(Human),
|
||||||
|
#[graphql(with = Character::droid_from_context)]
|
||||||
|
Droid(Droid),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Character {
|
||||||
|
// NOTICE: The function signature must contain `&self` and `&Context`,
|
||||||
|
// and return `Option<&VariantType>`.
|
||||||
|
fn droid_from_context<'c>(&self, ctx: &'c CustomContext) -> Option<&'c Droid> {
|
||||||
|
Some(&ctx.droid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
With an external resolver function we can even declare a new [GraphQL union][1] variant where the Rust type is absent in the initial enum definition. The attribute syntax `#[graphql(on VariantType = resolver_fn)]` follows the [GraphQL syntax for dispatching union variants](https://spec.graphql.org/June2018/#example-f8163).
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(dead_code)]
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::{GraphQLObject, GraphQLUnion};
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(Context = CustomContext)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(Context = CustomContext)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
primary_function: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(Context = CustomContext)]
|
||||||
|
struct Ewok {
|
||||||
|
id: String,
|
||||||
|
is_funny: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CustomContext {
|
||||||
|
ewok: Ewok,
|
||||||
|
}
|
||||||
|
impl juniper::Context for CustomContext {}
|
||||||
|
|
||||||
|
#[derive(GraphQLUnion)]
|
||||||
|
#[graphql(Context = CustomContext)]
|
||||||
|
#[graphql(on Ewok = Character::ewok_from_context)]
|
||||||
|
enum Character {
|
||||||
|
Human(Human),
|
||||||
|
Droid(Droid),
|
||||||
|
#[graphql(ignore)] // or `#[graphql(skip)]`, your choice
|
||||||
|
Ewok,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Character {
|
||||||
|
fn ewok_from_context<'c>(&self, ctx: &'c CustomContext) -> Option<&'c Ewok> {
|
||||||
|
if let Self::Ewok = self {
|
||||||
|
Some(&ctx.ewok)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Structs
|
||||||
|
|
||||||
|
Using Rust structs as [GraphQL unions][1] is very similar to using enums, with the nuance that specifying an external resolver function is the only way to declare a [GraphQL union][1] variant.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use std::collections::HashMap;
|
||||||
|
use juniper::{GraphQLObject, GraphQLUnion};
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(Context = Database)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(Context = Database)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
primary_function: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Database {
|
||||||
|
humans: HashMap<String, Human>,
|
||||||
|
droids: HashMap<String, Droid>,
|
||||||
|
}
|
||||||
|
impl juniper::Context for Database {}
|
||||||
|
|
||||||
|
#[derive(GraphQLUnion)]
|
||||||
|
#[graphql(
|
||||||
|
Context = Database,
|
||||||
|
on Human = Character::get_human,
|
||||||
|
on Droid = Character::get_droid,
|
||||||
|
)]
|
||||||
|
struct Character {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Character {
|
||||||
|
fn get_human<'db>(&self, ctx: &'db Database) -> Option<&'db Human>{
|
||||||
|
ctx.humans.get(&self.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_droid<'db>(&self, ctx: &'db Database) -> Option<&'db Droid>{
|
||||||
|
ctx.droids.get(&self.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Traits
|
||||||
|
|
||||||
|
To use a Rust trait definition as a [GraphQL union][1] you need to use the `#[graphql_union]` macro. [Rust doesn't allow derive macros on traits](https://doc.rust-lang.org/stable/reference/procedural-macros.html#derive-macros), so using `#[derive(GraphQLUnion)]` on traits doesn't work.
|
||||||
|
|
||||||
|
> __NOTICE__:
|
||||||
|
> A __trait has to be [object safe](https://doc.rust-lang.org/stable/reference/items/traits.html#object-safety)__, because schema resolvers will need to return a [trait object](https://doc.rust-lang.org/stable/reference/types/trait-object.html) to specify a [GraphQL union][1] behind it.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::{graphql_union, GraphQLObject};
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
primary_function: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[graphql_union]
|
||||||
|
trait Character {
|
||||||
|
// NOTICE: The method signature must contain `&self` and return `Option<&VariantType>`.
|
||||||
|
fn as_human(&self) -> Option<&Human> { None }
|
||||||
|
fn as_droid(&self) -> Option<&Droid> { None }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Character for Human {
|
||||||
|
fn as_human(&self) -> Option<&Human> { Some(&self) }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Character for Droid {
|
||||||
|
fn as_droid(&self) -> Option<&Droid> { Some(&self) }
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Custom context
|
||||||
|
|
||||||
|
If a [`Context`][6] is required in a trait method to resolve a [GraphQL union][1] variant, specify it as an argument.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(unused_variables)]
|
||||||
|
# extern crate juniper;
|
||||||
|
# use std::collections::HashMap;
|
||||||
|
use juniper::{graphql_union, GraphQLObject};
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(Context = Database)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(Context = Database)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
primary_function: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Database {
|
||||||
|
humans: HashMap<String, Human>,
|
||||||
|
droids: HashMap<String, Droid>,
|
||||||
|
}
|
||||||
|
impl juniper::Context for Database {}
|
||||||
|
|
||||||
|
#[graphql_union(context = Database)]
|
||||||
|
trait Character {
|
||||||
|
// NOTICE: The method signature may optionally contain `&Context`.
|
||||||
|
fn as_human<'db>(&self, ctx: &'db Database) -> Option<&'db Human> { None }
|
||||||
|
fn as_droid<'db>(&self, ctx: &'db Database) -> Option<&'db Droid> { None }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Character for Human {
|
||||||
|
fn as_human<'db>(&self, ctx: &'db Database) -> Option<&'db Human> {
|
||||||
|
ctx.humans.get(&self.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Character for Droid {
|
||||||
|
fn as_droid<'db>(&self, ctx: &'db Database) -> Option<&'db Droid> {
|
||||||
|
ctx.droids.get(&self.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Ignoring trait methods
|
||||||
|
|
||||||
|
As with enums, we may want to omit some trait methods to be assumed as [GraphQL union][1] variants and ignore them.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::{graphql_union, GraphQLObject};
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
primary_function: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[graphql_union]
|
||||||
|
trait Character {
|
||||||
|
fn as_human(&self) -> Option<&Human> { None }
|
||||||
|
fn as_droid(&self) -> Option<&Droid> { None }
|
||||||
|
#[graphql(ignore)] // or `#[graphql(skip)]`, your choice
|
||||||
|
fn id(&self) -> &str;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Character for Human {
|
||||||
|
fn as_human(&self) -> Option<&Human> { Some(&self) }
|
||||||
|
fn id(&self) -> &str { self.id.as_str() }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Character for Droid {
|
||||||
|
fn as_droid(&self) -> Option<&Droid> { Some(&self) }
|
||||||
|
fn id(&self) -> &str { self.id.as_str() }
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### External resolver functions
|
||||||
|
|
||||||
|
Similarly to enums and structs, it's not mandatory to use trait methods as [GraphQL union][1] variant resolvers. Instead, custom functions may be specified:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# extern crate juniper;
|
||||||
|
# use std::collections::HashMap;
|
||||||
|
use juniper::{graphql_union, GraphQLObject};
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(Context = Database)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(Context = Database)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
primary_function: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Database {
|
||||||
|
humans: HashMap<String, Human>,
|
||||||
|
droids: HashMap<String, Droid>,
|
||||||
|
}
|
||||||
|
impl juniper::Context for Database {}
|
||||||
|
|
||||||
|
#[graphql_union(context = Database)]
|
||||||
|
#[graphql_union(
|
||||||
|
on Human = DynCharacter::get_human,
|
||||||
|
on Droid = get_droid,
|
||||||
|
)]
|
||||||
|
trait Character {
|
||||||
|
#[graphql(ignore)] // or `#[graphql(skip)]`, your choice
|
||||||
|
fn id(&self) -> &str;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Character for Human {
|
||||||
|
fn id(&self) -> &str { self.id.as_str() }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Character for Droid {
|
||||||
|
fn id(&self) -> &str { self.id.as_str() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// The trait object is always `Send` and `Sync`.
|
||||||
|
type DynCharacter<'a> = dyn Character + Send + Sync + 'a;
|
||||||
|
|
||||||
|
impl<'a> DynCharacter<'a> {
|
||||||
|
fn get_human<'db>(&self, ctx: &'db Database) -> Option<&'db Human> {
|
||||||
|
ctx.humans.get(self.id())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// External resolver function doesn't have to be a method of a type.
|
||||||
|
// It's only a matter of the function signature to match the requirements.
|
||||||
|
fn get_droid<'db>(ch: &DynCharacter<'_>, ctx: &'db Database) -> Option<&'db Droid> {
|
||||||
|
ctx.droids.get(ch.id())
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## `ScalarValue` considerations
|
||||||
|
|
||||||
|
By default, `#[derive(GraphQLUnion)]` and `#[graphql_union]` macros generate code, which is generic over a [`ScalarValue`][2] type. This may introduce a problem when at least one of [GraphQL union][1] variants is restricted to a concrete [`ScalarValue`][2] type in its implementation. To resolve such problem, a concrete [`ScalarValue`][2] type should be specified:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# #![allow(dead_code)]
|
||||||
|
# extern crate juniper;
|
||||||
|
use juniper::{DefaultScalarValue, GraphQLObject, GraphQLUnion};
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
#[graphql(Scalar = DefaultScalarValue)]
|
||||||
|
struct Human {
|
||||||
|
id: String,
|
||||||
|
home_planet: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLObject)]
|
||||||
|
struct Droid {
|
||||||
|
id: String,
|
||||||
|
primary_function: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(GraphQLUnion)]
|
||||||
|
#[graphql(Scalar = DefaultScalarValue)] // removing this line will fail compilation
|
||||||
|
enum Character {
|
||||||
|
Human(Human),
|
||||||
|
Droid(Droid),
|
||||||
|
}
|
||||||
|
#
|
||||||
|
# fn main() {}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
[1]: https://spec.graphql.org/June2018/#sec-Unions
|
||||||
|
[2]: https://docs.rs/juniper/latest/juniper/trait.ScalarValue.html
|
||||||
|
[5]: https://spec.graphql.org/June2018/#sec-Interfaces
|
||||||
|
[6]: https://docs.rs/juniper/0.14.2/juniper/trait.Context.html
|
3
docs/book/tests/.gitignore
vendored
Normal file
3
docs/book/tests/.gitignore
vendored
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
/target/
|
||||||
|
**/*.rs.bk
|
||||||
|
Cargo.lock
|
26
docs/book/tests/Cargo.toml
Normal file
26
docs/book/tests/Cargo.toml
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
[package]
|
||||||
|
name = "juniper_book_tests"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2018"
|
||||||
|
authors = ["Magnus Hallin <mhallin@fastmail.com>"]
|
||||||
|
build = "build.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
juniper = { path = "../../../juniper" }
|
||||||
|
juniper_iron = { path = "../../../juniper_iron" }
|
||||||
|
juniper_subscriptions = { path = "../../../juniper_subscriptions" }
|
||||||
|
|
||||||
|
derive_more = "0.99"
|
||||||
|
futures = "0.3"
|
||||||
|
iron = "0.5"
|
||||||
|
mount = "0.4"
|
||||||
|
skeptic = "0.13"
|
||||||
|
serde_json = "1.0"
|
||||||
|
tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync"] }
|
||||||
|
uuid = "0.8"
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
skeptic = "0.13"
|
||||||
|
|
||||||
|
[patch.crates-io]
|
||||||
|
juniper_codegen = { path = "../../../juniper_codegen" }
|
4
docs/book/tests/build.rs
Normal file
4
docs/book/tests/build.rs
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
fn main() {
|
||||||
|
let files = skeptic::markdown_files_of_directory("../content/");
|
||||||
|
skeptic::generate_doc_tests(&files);
|
||||||
|
}
|
3
docs/book/tests/src/lib.rs
Normal file
3
docs/book/tests/src/lib.rs
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
#![deny(warnings)]
|
||||||
|
|
||||||
|
include!(concat!(env!("OUT_DIR"), "/skeptic-tests.rs"));
|
20
examples/actix_subscriptions/Cargo.toml
Normal file
20
examples/actix_subscriptions/Cargo.toml
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
[package]
|
||||||
|
name = "actix_subscriptions"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2018"
|
||||||
|
authors = ["Mihai Dinculescu <mihai.dinculescu@outlook.com>"]
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
actix-web = "4.0.0-beta.12"
|
||||||
|
actix-cors = "0.6.0-beta.4"
|
||||||
|
futures = "0.3"
|
||||||
|
env_logger = "0.9"
|
||||||
|
serde = "1.0"
|
||||||
|
serde_json = "1.0"
|
||||||
|
rand = "0.8"
|
||||||
|
tokio = "1.0"
|
||||||
|
async-stream = "0.3"
|
||||||
|
juniper = { path = "../../juniper", features = ["expose-test-schema"] }
|
||||||
|
juniper_actix = { path = "../../juniper_actix", features = ["subscriptions"] }
|
||||||
|
juniper_graphql_ws = { path = "../../juniper_graphql_ws" }
|
15
examples/actix_subscriptions/Makefile.toml
Normal file
15
examples/actix_subscriptions/Makefile.toml
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
[tasks.run]
|
||||||
|
disabled = true
|
||||||
|
|
||||||
|
[tasks.release]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-some]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-local-test]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-some-local-test]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-dry-run]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-some-dry-run]
|
||||||
|
disabled = true
|
|
@ -1,5 +1,3 @@
|
||||||
//! This example demonstrates asynchronous subscriptions with [`actix_web`].
|
|
||||||
|
|
||||||
use std::{env, pin::Pin, time::Duration};
|
use std::{env, pin::Pin, time::Duration};
|
||||||
|
|
||||||
use actix_cors::Cors;
|
use actix_cors::Cors;
|
||||||
|
@ -7,15 +5,15 @@ use actix_web::{
|
||||||
http::header,
|
http::header,
|
||||||
middleware,
|
middleware,
|
||||||
web::{self, Data},
|
web::{self, Data},
|
||||||
App, Error, HttpRequest, HttpResponse, HttpServer, Responder,
|
App, Error, HttpRequest, HttpResponse, HttpServer,
|
||||||
};
|
};
|
||||||
|
|
||||||
use juniper::{
|
use juniper::{
|
||||||
graphql_subscription, graphql_value,
|
graphql_object, graphql_subscription, graphql_value,
|
||||||
tests::fixtures::starwars::schema::{Database, Query},
|
tests::fixtures::starwars::schema::{Character as _, Database, Query},
|
||||||
EmptyMutation, FieldError, GraphQLObject, RootNode,
|
EmptyMutation, FieldError, RootNode,
|
||||||
};
|
};
|
||||||
use juniper_actix::{graphiql_handler, graphql_handler, playground_handler, subscriptions};
|
use juniper_actix::{graphql_handler, playground_handler, subscriptions::subscriptions_handler};
|
||||||
use juniper_graphql_ws::ConnectionConfig;
|
use juniper_graphql_ws::ConnectionConfig;
|
||||||
|
|
||||||
type Schema = RootNode<'static, Query, EmptyMutation<Database>, Subscription>;
|
type Schema = RootNode<'static, Query, EmptyMutation<Database>, Subscription>;
|
||||||
|
@ -28,61 +26,41 @@ async fn playground() -> Result<HttpResponse, Error> {
|
||||||
playground_handler("/graphql", Some("/subscriptions")).await
|
playground_handler("/graphql", Some("/subscriptions")).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn graphiql() -> Result<HttpResponse, Error> {
|
|
||||||
graphiql_handler("/graphql", Some("/subscriptions")).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn graphql(
|
async fn graphql(
|
||||||
req: HttpRequest,
|
req: actix_web::HttpRequest,
|
||||||
payload: web::Payload,
|
payload: actix_web::web::Payload,
|
||||||
schema: Data<Schema>,
|
schema: web::Data<Schema>,
|
||||||
) -> Result<HttpResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let context = Database::new();
|
let context = Database::new();
|
||||||
graphql_handler(&schema, &context, req, payload).await
|
graphql_handler(&schema, &context, req, payload).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn homepage() -> impl Responder {
|
|
||||||
HttpResponse::Ok()
|
|
||||||
.insert_header(("content-type", "text/html"))
|
|
||||||
.message_body(
|
|
||||||
"<html><h1>juniper_actix/subscription example</h1>\
|
|
||||||
<div>visit <a href=\"/graphiql\">GraphiQL</a></div>\
|
|
||||||
<div>visit <a href=\"/playground\">GraphQL Playground</a></div>\
|
|
||||||
</html>",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn subscriptions(
|
|
||||||
req: HttpRequest,
|
|
||||||
stream: web::Payload,
|
|
||||||
schema: web::Data<Schema>,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
|
||||||
let context = Database::new();
|
|
||||||
let schema = schema.into_inner();
|
|
||||||
let config = ConnectionConfig::new(context);
|
|
||||||
// set the keep alive interval to 15 secs so that it doesn't timeout in playground
|
|
||||||
// playground has a hard-coded timeout set to 20 secs
|
|
||||||
let config = config.with_keep_alive_interval(Duration::from_secs(15));
|
|
||||||
|
|
||||||
subscriptions::ws_handler(req, stream, schema, config).await
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Subscription;
|
struct Subscription;
|
||||||
|
|
||||||
#[derive(GraphQLObject)]
|
|
||||||
struct RandomHuman {
|
struct RandomHuman {
|
||||||
id: String,
|
id: String,
|
||||||
name: String,
|
name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: remove this when async interfaces are merged
|
||||||
|
#[graphql_object(context = Database)]
|
||||||
|
impl RandomHuman {
|
||||||
|
fn id(&self) -> &str {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
&self.name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type RandomHumanStream =
|
type RandomHumanStream =
|
||||||
Pin<Box<dyn futures::Stream<Item = Result<RandomHuman, FieldError>> + Send>>;
|
Pin<Box<dyn futures::Stream<Item = Result<RandomHuman, FieldError>> + Send>>;
|
||||||
|
|
||||||
#[graphql_subscription(context = Database)]
|
#[graphql_subscription(context = Database)]
|
||||||
impl Subscription {
|
impl Subscription {
|
||||||
#[graphql(
|
#[graphql(
|
||||||
description = "A random humanoid creature in the Star Wars universe every 3 seconds. \
|
description = "A random humanoid creature in the Star Wars universe every 3 seconds. Second result will be an error."
|
||||||
Second result will be an error."
|
|
||||||
)]
|
)]
|
||||||
async fn random_human(context: &Database) -> RandomHumanStream {
|
async fn random_human(context: &Database) -> RandomHumanStream {
|
||||||
let mut counter = 0;
|
let mut counter = 0;
|
||||||
|
@ -106,8 +84,8 @@ impl Subscription {
|
||||||
let human = context.get_human(&random_id).unwrap().clone();
|
let human = context.get_human(&random_id).unwrap().clone();
|
||||||
|
|
||||||
yield Ok(RandomHuman {
|
yield Ok(RandomHuman {
|
||||||
id: human.id().into(),
|
id: human.id().to_owned(),
|
||||||
name: human.name().unwrap().into(),
|
name: human.name().unwrap().to_owned(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -117,6 +95,21 @@ impl Subscription {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn subscriptions(
|
||||||
|
req: HttpRequest,
|
||||||
|
stream: web::Payload,
|
||||||
|
schema: web::Data<Schema>,
|
||||||
|
) -> Result<HttpResponse, Error> {
|
||||||
|
let context = Database::new();
|
||||||
|
let schema = schema.into_inner();
|
||||||
|
let config = ConnectionConfig::new(context);
|
||||||
|
// set the keep alive interval to 15 secs so that it doesn't timeout in playground
|
||||||
|
// playground has a hard-coded timeout set to 20 secs
|
||||||
|
let config = config.with_keep_alive_interval(Duration::from_secs(15));
|
||||||
|
|
||||||
|
subscriptions_handler(req, stream, schema, config).await
|
||||||
|
}
|
||||||
|
|
||||||
#[actix_web::main]
|
#[actix_web::main]
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
env::set_var("RUST_LOG", "info");
|
env::set_var("RUST_LOG", "info");
|
||||||
|
@ -143,10 +136,13 @@ async fn main() -> std::io::Result<()> {
|
||||||
.route(web::get().to(graphql)),
|
.route(web::get().to(graphql)),
|
||||||
)
|
)
|
||||||
.service(web::resource("/playground").route(web::get().to(playground)))
|
.service(web::resource("/playground").route(web::get().to(playground)))
|
||||||
.service(web::resource("/graphiql").route(web::get().to(graphiql)))
|
.default_service(web::route().to(|| {
|
||||||
.default_service(web::to(homepage))
|
HttpResponse::Found()
|
||||||
|
.append_header((header::LOCATION, "/playground"))
|
||||||
|
.finish()
|
||||||
|
}))
|
||||||
})
|
})
|
||||||
.bind("127.0.0.1:8080")?
|
.bind(format!("{}:{}", "127.0.0.1", 8080))?
|
||||||
.run()
|
.run()
|
||||||
.await
|
.await
|
||||||
}
|
}
|
1
examples/basic_subscriptions/.gitignore
vendored
Normal file
1
examples/basic_subscriptions/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
target
|
15
examples/basic_subscriptions/Cargo.toml
Normal file
15
examples/basic_subscriptions/Cargo.toml
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
[package]
|
||||||
|
name = "basic_subscriptions"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2018"
|
||||||
|
publish = false
|
||||||
|
authors = ["Jordao Rosario <jordao.rosario01@gmail.com>"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
futures = "0.3"
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
serde_json = "1.0"
|
||||||
|
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||||
|
|
||||||
|
juniper = { path = "../../juniper" }
|
||||||
|
juniper_subscriptions = { path = "../../juniper_subscriptions" }
|
15
examples/basic_subscriptions/Makefile.toml
Normal file
15
examples/basic_subscriptions/Makefile.toml
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
[tasks.run]
|
||||||
|
disabled = true
|
||||||
|
|
||||||
|
[tasks.release]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-some]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-local-test]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-some-local-test]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-dry-run]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-some-dry-run]
|
||||||
|
disabled = true
|
|
@ -16,7 +16,7 @@ impl juniper::Context for Database {}
|
||||||
|
|
||||||
impl Database {
|
impl Database {
|
||||||
fn new() -> Self {
|
fn new() -> Self {
|
||||||
Self
|
Self {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -45,7 +45,7 @@ impl Subscription {
|
||||||
type Schema = RootNode<'static, Query, EmptyMutation<Database>, Subscription>;
|
type Schema = RootNode<'static, Query, EmptyMutation<Database>, Subscription>;
|
||||||
|
|
||||||
fn schema() -> Schema {
|
fn schema() -> Schema {
|
||||||
Schema::new(Query, EmptyMutation::new(), Subscription)
|
Schema::new(Query {}, EmptyMutation::new(), Subscription {})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
1
examples/warp_async/.gitignore
vendored
Normal file
1
examples/warp_async/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
target
|
17
examples/warp_async/Cargo.toml
Normal file
17
examples/warp_async/Cargo.toml
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
[package]
|
||||||
|
name = "warp_async"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2018"
|
||||||
|
publish = false
|
||||||
|
authors = ["Christoph Herzog <chris@theduke.at>"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
juniper = { path = "../../juniper" }
|
||||||
|
juniper_warp = { path = "../../juniper_warp" }
|
||||||
|
|
||||||
|
env_logger = "0.9"
|
||||||
|
futures = "0.3.1"
|
||||||
|
log = "0.4.8"
|
||||||
|
reqwest = { version = "0.11", features = ["rustls-tls"] }
|
||||||
|
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||||
|
warp = "0.3"
|
15
examples/warp_async/Makefile.toml
Normal file
15
examples/warp_async/Makefile.toml
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
[tasks.run]
|
||||||
|
disabled = true
|
||||||
|
|
||||||
|
[tasks.release]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-some]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-local-test]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-some-local-test]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-dry-run]
|
||||||
|
disabled = true
|
||||||
|
[tasks.release-some-dry-run]
|
||||||
|
disabled = true
|
104
examples/warp_async/src/main.rs
Normal file
104
examples/warp_async/src/main.rs
Normal file
|
@ -0,0 +1,104 @@
|
||||||
|
//! This example demonstrates async/await usage with warp.
|
||||||
|
|
||||||
|
use juniper::{
|
||||||
|
graphql_object, EmptyMutation, EmptySubscription, FieldError, GraphQLEnum, RootNode,
|
||||||
|
};
|
||||||
|
use warp::{http::Response, Filter};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
struct Context;
|
||||||
|
impl juniper::Context for Context {}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, GraphQLEnum)]
|
||||||
|
enum UserKind {
|
||||||
|
Admin,
|
||||||
|
User,
|
||||||
|
Guest,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct User {
|
||||||
|
id: i32,
|
||||||
|
kind: UserKind,
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[graphql_object(context = Context)]
|
||||||
|
impl User {
|
||||||
|
fn id(&self) -> i32 {
|
||||||
|
self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn kind(&self) -> UserKind {
|
||||||
|
self.kind
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
&self.name
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn friends(&self) -> Vec<User> {
|
||||||
|
vec![]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
struct Query;
|
||||||
|
|
||||||
|
#[graphql_object(context = Context)]
|
||||||
|
impl Query {
|
||||||
|
async fn users() -> Vec<User> {
|
||||||
|
vec![User {
|
||||||
|
id: 1,
|
||||||
|
kind: UserKind::Admin,
|
||||||
|
name: "user1".into(),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch a URL and return the response body text.
|
||||||
|
async fn request(url: String) -> Result<String, FieldError> {
|
||||||
|
Ok(reqwest::get(&url).await?.text().await?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Schema = RootNode<'static, Query, EmptyMutation<Context>, EmptySubscription<Context>>;
|
||||||
|
|
||||||
|
fn schema() -> Schema {
|
||||||
|
Schema::new(
|
||||||
|
Query,
|
||||||
|
EmptyMutation::<Context>::new(),
|
||||||
|
EmptySubscription::<Context>::new(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
std::env::set_var("RUST_LOG", "warp_async");
|
||||||
|
env_logger::init();
|
||||||
|
|
||||||
|
let log = warp::log("warp_server");
|
||||||
|
|
||||||
|
let homepage = warp::path::end().map(|| {
|
||||||
|
Response::builder()
|
||||||
|
.header("content-type", "text/html")
|
||||||
|
.body(
|
||||||
|
"<html><h1>juniper_warp</h1><div>visit <a href=\"/graphiql\">/graphiql</a></html>",
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
log::info!("Listening on 127.0.0.1:8080");
|
||||||
|
|
||||||
|
let state = warp::any().map(|| Context);
|
||||||
|
let graphql_filter = juniper_warp::make_graphql_filter(schema(), state.boxed());
|
||||||
|
|
||||||
|
warp::serve(
|
||||||
|
warp::get()
|
||||||
|
.and(warp::path("graphiql"))
|
||||||
|
.and(juniper_warp::graphiql_filter("/graphql", None))
|
||||||
|
.or(homepage)
|
||||||
|
.or(warp::path("graphql").and(graphql_filter))
|
||||||
|
.with(log),
|
||||||
|
)
|
||||||
|
.run(([127, 0, 0, 1], 8080))
|
||||||
|
.await
|
||||||
|
}
|
1
examples/warp_subscriptions/.gitignore
vendored
Normal file
1
examples/warp_subscriptions/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
target
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue