Unverified Commit 6ac2f4b7 authored by Arnar Kári Ágústsson's avatar Arnar Kári Ágústsson Committed by GitHub

With reason relay example (#12080)

* Add with-reason-relay example

* update gitignore

* Add missing components

* Add _app.js wrapper

* Move records to wait for results

* Update readme

* Upload schema

* Add call to query hook to get viewerData with getFragmentRefs

* Move relay env setup to seperate module

* remove unused code

* lint fixes

* prettier fix
parent b91e570a
{
"presets": [
"next/babel"
],
"plugins": [
"relay"
]
}
\ No newline at end of file
RELAY_ENDPOINT=https://api.graph.cool/relay/v1/next-js-with-relay-modern-example
__generated__/
schema/schema.graphql
lib/
.merlin
*.bs.js
{
"schemaPath": "schema/schema.graphql",
"extensions": {
"endpoints": {
"dev": "https://api.graph.cool/relay/v1/next-js-with-relay-modern-example"
}
}
}
\ No newline at end of file
# Reason Relay Example
[Reason Relay](https://reason-relay-documentation.zth.now.sh/)
This example relies on [graph.cool](https://www.graph.cool) for its GraphQL backend.
## Deploy your own
Deploy the example using [ZEIT Now](https://zeit.co/now):
[![Deploy with ZEIT Now](https://zeit.co/button)](https://zeit.co/import/project?template=https://github.com/zeit/next.js/tree/canary/examples/with-reason-relay)
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npm init next-app --example with-reason-relay with-reason-relay
# or
yarn create next-app --example with-reason-relay with-reason-relay
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-reason-relay
cd with-reason-relay
```
Install it:
```bash
npm install
# or
yarn
```
Download schema introspection data from configured Relay endpoint
```bash
npm run schema
# or
yarn schema
```
Run Relay ahead-of-time compilation (should be re-run after any edits to components that query data with Relay)
```bash
npm run relay
# or
yarn relay
```
Build the project
```bash
npm run build
# or
yarn build
```
Run the project
```bash
npm run dev
# or
yarn dev
```
Deploy it to the cloud with [ZEIT Now](https://zeit.co/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
{
"name": "with-reason-relay",
"refmt": 3,
"reason": {
"react-jsx": 3
},
"package-specs": {
"module": "commonjs",
"in-source": true
},
"suffix": ".bs.js",
"sources": [
{
"dir": "pages",
"subdirs": true
},
{
"dir": "src",
"subdirs": true
}
],
"bs-dependencies": [
"bs-fetch",
"reason-react",
"reason-relay",
"reason-promise"
],
"ppx-flags": ["reason-relay/ppx"]
}
require('dotenv').config()
const path = require('path')
const Dotenv = require('dotenv-webpack')
module.exports = {
webpack: config => {
config.plugins = config.plugins || []
config.plugins = [
...config.plugins,
// Read the .env file
new Dotenv({
path: path.join(__dirname, '.env'),
systemvars: true,
}),
]
return config
},
}
{
"name": "with-relay-modern",
"version": "3.0.4",
"description": "Example of Next.js with Relay Modern SSR",
"scripts": {
"graphcool-init": "graphcool init --schema schema/init-schema.graphql",
"dev": "next",
"build": "bsb -make-world",
"next": "next",
"start": "next start",
"relay": "reason-relay-compiler",
"schema": "graphql get-schema -e dev"
},
"author": "arnarkari93@gmail.com",
"license": "ISC",
"dependencies": {
"@zeit/next-css": "1.0.1",
"bs-fetch": "0.5.2",
"bs-platform": "7.2.2",
"dotenv": "^8.2.0",
"dotenv-webpack": "^1.7.0",
"graphql": "15.0.0",
"isomorphic-unfetch": "^3.0.0",
"next": "latest",
"next-transpile-modules": "3.2.0",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-relay": "0.0.0-experimental-8cc94ddc",
"reason-promise": "1.0.2",
"reason-react": "0.7.0",
"reason-relay": "0.8.2",
"relay-config": "9.0.0",
"relay-runtime": "9.0.0"
},
"devDependencies": {
"babel-plugin-relay": "^9.0.0",
"graphcool": "^1.4.0",
"graphql-cli": "^3.0.14",
"relay-compiler": "9.0.0"
},
"resolutions": {
"graphql": "15.0.0",
"react": "0.0.0-experimental-e5d06e34b",
"react-dom": "0.0.0-experimental-e5d06e34b"
}
}
module Next = {
let inject = (_cls: Js.t({..}) => React.element, _fn) => [%bs.raw
{| _cls.getInitialProps = _fn |}
];
};
module BlogPostsPage = {
[@react.component]
let make = () => {
let viewerData = Query.Viewer.use(~variables=(), ());
<BlogPosts viewer={viewerData.viewer.getFragmentRefs()} />;
};
};
[@react.component]
let make = (~records) => {
<ReasonRelay.Context.Provider environment={RelayEnv.createEnvironment(~records, ())}>
<div> <BlogPostsPage /> </div>
</ReasonRelay.Context.Provider>;
};
let getInitialProps = _context => {
let environment = RelayEnv.createEnvironment();
let promise = Query.Viewer.fetchPromised(~environment, ~variables=());
Promise.mapOk(
promise,
_p => {
let records =
environment
->ReasonRelay.Environment.getStore
->ReasonRelay.Store.getSource
->ReasonRelay.RecordSource.toJSON;
{"records": records};
},
)
->Promise.Js.toBsPromise;
};
let default = make;
Next.inject(default, getInitialProps);
import React from 'react'
import App from 'next/app'
const isStatusCodeOk = res => {
try {
return `${res.statusCode}`.startsWith('2')
} catch (e) {
return true
}
}
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return {
pageProps,
path: ctx.asPath,
isOk: isStatusCodeOk(ctx.res),
}
}
render() {
const { Component, pageProps, isOk } = this.props
return isOk ? (
<div>
<Component {...pageProps[0]} />
</div>
) : (
/* ⚠️ Important to only render these components when statusCode is NOT ok */
<Component {...pageProps[0]} />
)
}
}
export default MyApp
// relay.config.js
module.exports = {
src: './src', // Path to the folder containing your Reason files
schema: './schema/schema.graphql', // Path to the schema.graphql you've exported from your API. Don't know what this is? It's a saved introspection of what your schema looks like. You can run `npx get-graphql-schema http://path/to/my/graphql/server > schema.graphql` in your root to generate it
artifactDirectory: './src/__generated__', // The directory where all generated files will be emitted
// You can add type definitions for custom scalars here.
// Whenever a custom scalar is encountered, the type emitted will correspond to the definition defined here. You can then deal with the type as needed when accessing the data.
}
type BlogPost implements Node {
content: String!
createdAt: DateTime!
id: ID! @isUnique
title: String!
updatedAt: DateTime!
}
\ No newline at end of file
This diff is collapsed.
module Fragment = [%relay.fragment
{|
fragment BlogPostPreview_fragment on BlogPost {
id
title
}
|}
];
[@react.component]
let make = (~post) => {
let fragment = Fragment.use(post);
<li> {React.string(fragment.title)} </li>;
};
module Fragment = [%relay.fragment {|
fragment BlogPosts_fragment on Viewer {
allBlogPosts(first: 10, orderBy: createdAt_DESC) {
edges {
node {
...BlogPostPreview_fragment
id
}
}
}
}
|}];
[@react.component]
let make = (~viewer) => {
let fragment = Fragment.use(viewer);
<div>
<h1>{React.string("Blog posts")}</h1>
<ul>
{switch (fragment.allBlogPosts.edges) {
| Some(posts) => {
Belt.Array.map(posts, post => {
switch (post) {
| None => React.null
| Some(p) =>
<BlogPostPreview key={p.node.id} post={p.node.getFragmentRefs()} />
}
})->React.array
}
| None => <li>{React.string("No posts found")}</li>
}}
</ul>
</div>
};
module Viewer =[%relay.query {|
query Query_Query {
viewer {
...BlogPosts_fragment
}
}
|}];
open Fetch;
[%raw "require('isomorphic-fetch')"];
/* RelayEnv.re */
/* This is just a custom exception to indicate that something went wrong. */
exception Graphql_error(string);
/**
* A standard fetch that sends our operation and variables to the
* GraphQL server, and then decodes and returns the response.
*/
let fetchQuery: ReasonRelay.Network.fetchFunctionPromise =
(operation, variables, _cacheConfig) => {
let uri: string = [%raw "process.env.RELAY_ENDPOINT"];
fetchWithInit(
uri,
RequestInit.make(
~method_=Post,
~body=
Js.Dict.fromList([
("query", Js.Json.string(operation.text)),
("variables", variables),
])
|> Js.Json.object_
|> Js.Json.stringify
|> BodyInit.make,
~headers=
HeadersInit.make({
"content-type": "application/json",
"accept": "application/json",
}),
(),
),
)
|> Js.Promise.then_(resp =>
if (Response.ok(resp)) {
Response.json(resp);
} else {
Js.Promise.reject(
Graphql_error("Request failed: " ++ Response.statusText(resp)),
);
}
);
};
let createEnvironment = (~records=?, ()) => {
let source = ReasonRelay.RecordSource.make(~records?, ());
let store = ReasonRelay.Store.make(~source, ());
let network =
ReasonRelay.Network.makePromiseBased(~fetchFunction=fetchQuery, ());
ReasonRelay.Environment.make(~network, ~store, ());
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment