Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions examples/with-fauna/.env.local.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
FAUNA_ADMIN_KEY=<replace-with-your-admin-key>
SESSION_KEY=
OAUTH_CLIENT_KEY=
OAUTH_CLIENT_SECRET=
57 changes: 57 additions & 0 deletions examples/with-fauna/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Fauna GraphQL Guestbook Starter

This Guestbook Single-Page Application (SPA) example shows you how to use [Fauna's GraphQL endpoint](https://docs.fauna.com/fauna/current/api/graphql/) in your Next.js project.

## Deploy your own

Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-fauna&project-name=fauna-nextjs-guestbook&repository-name=fauna-nextjs-guestbook&demo-title=Next.js%20Fauna%20Guestbook%20App&demo-description=A%20simple%20guestbook%20application%20built%20with%20Next.js%20and%20Fauna&integration-ids=oac_Erlbqm8Teb1y4WhioE3r2utY)

## Why Fauna

By importing a `.gql` or `.graphql` schema into Fauna ([see our sample schema file](./schema.gql)), Fauna will generate required Indexes and GraphQL resolvers for you -- hands free 👐 ([some limitations exist](https://docs.fauna.com/fauna/current/api/graphql/#limitations)).

## How to use

You can start with this template [using `create-next-app`](#using-create-next-app) or by [downloading the repository manually](#download-manually).

To use a live Fauna database, create a database at [dashboard.fauna.com](https://dashboard.fauna.com/) and generate an admin token by going to the **Security** tab on the left and then click **New Key**. Give the new key a name and select the 'Admin' Role. Copy the token since the setup script will ask for it. Do not use it in the frontend, it has superpowers which you don't want to give to your users.

The database can then be set up with the delivered setup by running:

```
npm run setup
# or
yarn setup
```

This script will ask for the admin token. Once you provide it with a valid token, this is what the script automatically does for you:

- **Import the GraphQL schema**, by importing a GraphQL schema in Fauna, Fauna automatically sets up collections and indexes to support your queries. This is now done for you with this script but can also be done from the [dashboard.fauna.com](https://dashboard.fauna.com/) UI by going to the GraphQL tab
- **Create a role suitable for the Client**, Fauna has a security system that allows you to define which resources can be accessed for a specific token. That's how we limit our clients powers, feel free to look at the scripts/setup.js script to see how we make roles and tokens.
- **Create a token for that role** which is printed, this is the token to be used in the frontend.

At the end, a `.env.local` [file](https://nextjs.org/docs/basic-features/environment-variables) will be created for you with the newly generated client token assigned to an environment variable.

Execute [`create-next-app`](https://github.com/vercel/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:

```
npx create-next-app --example with-graphql-fauna with-graphql-fauna-app
# or
yarn create next-app --example with-graphql-fauna with-graphql-fauna-app
```

### Run locally

Install packages, then run the development server:

```bash
npm install
npm run dev
# or
yarn
yarn dev
```

Your app should be up and running on [http://localhost:3000](http://localhost:3000)!
19 changes: 19 additions & 0 deletions examples/with-fauna/components/ErrorMessage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export default function ErrorMessage({ children }) {
return (
<p className="flex items-center text-sm font-bold text-red-800 dark:text-red-400">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
className="mr-2 h-4 w-4"
>
<path
fillRule="evenodd"
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
clipRule="evenodd"
/>
</svg>
{children}
</p>
)
}
24 changes: 24 additions & 0 deletions examples/with-fauna/components/LoadingSpinner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export default function LoadingSpinner() {
return (
<svg
className="animate-spin h-5 w-5 text-gray-900 dark:text-gray-100"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
)
}
19 changes: 19 additions & 0 deletions examples/with-fauna/components/SuccessMessage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export default function SuccessMessage({ children }) {
return (
<p className="flex items-center text-sm font-bold text-green-700 dark:text-green-400">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
className="mr-2 h-4 w-4"
>
<path
fillRule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
clipRule="evenodd"
/>
</svg>
{children}
</p>
)
}
9 changes: 9 additions & 0 deletions examples/with-fauna/jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"],
"@/lib/*": ["lib/*"]
}
}
}
85 changes: 85 additions & 0 deletions examples/with-fauna/lib/fauna.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { GraphQLClient, gql } from 'graphql-request'

const graphQLClient = new GraphQLClient('https://graphql.fauna.com/graphql', {
headers: {
authorization: `Bearer ${process.env.FAUNA_ADMIN_KEY}`,
},
})

export const getGuestbookEntry = (id) => {
const query = gql`
query Entries($id: Int) {
entries(id: $id) {
data {
_id
_ts
email
body
created_by
updated_at
}
}
}
`

return graphQLClient.request(query, { size: 100 })
}

export const getAllGuestbookEntries = () => {
const query = gql`
query Entries($size: Int) {
entries(_size: $size) {
data {
_id
_ts
email
body
created_by
updated_at
}
}
}
`

return graphQLClient.request(query, { size: 100 })
}

export const createGuestbookEntry = async (newEntry) => {
const mutation = gql`
mutation CreateGuestbookEntry($twitterHandle: String!, $story: String!) {
createGuestbookEntry(
data: {
email: $email
body: $body
created_by: $created_by
updated_at: $updated_at
}
) {
_id
_ts
email
body
created_by
updated_at
}
}
`

return graphQLClient.request(mutation, newEntry)
}

export const updateGuestbookEntry = async (updatedEntry) => {
const mutation = gql`TODO`

return graphQLClient.request(mutation, updatedEntry)
}

export const deleteGuestbookEntry = async (id) => {
const mutation = gql`
mutation DeleteGuestbookEntry($id: Int!) {
deleteGuestbookEntry(data: { id: $id })
}
`

return graphQLClient.request(mutation, { id })
}
5 changes: 5 additions & 0 deletions examples/with-fauna/lib/fetcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default async function Fetcher(...args) {
const res = await fetch(...args)

return res.json()
}
11 changes: 11 additions & 0 deletions examples/with-fauna/lib/session.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import cookieSession from 'micro-cookie-session'

const session = cookieSession({
name: 'session',
keys: [process.env.SESSION_KEY],
maxAge: 24 * 60 * 60 * 1000,
})

export default function wrapper(req, res) {
session(req, res)
}
29 changes: 29 additions & 0 deletions examples/with-fauna/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "with-fauna",
"version": "1.0.0",
"license": "MIT",
"description": "Guestbook example with Next.js and Fauna.",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"setup": "node ./scripts/setup.js"
},
"dependencies": {
"date-fns": "2.22.1",
"graphql-request": "3.4.0",
"micro-cookie-session": "2.0.0-beta.1",
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"swr": "0.5.6"
},
"devDependencies": {
"autoprefixer": "10.2.6",
"faunadb": "2.11.1",
"postcss": "8.3.5",
"request": "2.88.2",
"stream-to-promise": "2.2.0",
"tailwindcss": "2.2.4"
}
}
59 changes: 59 additions & 0 deletions examples/with-fauna/pages/api/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import session from '@/lib/session'

const CLIENT_ID = process.env.OAUTH_CLIENT_KEY
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET

export default async function handler(req, res) {
session(req, res)

const { code } = req.query

if (!code) {
return res.redirect(
`https://github.com/login/oauth/authorize?client_id=${CLIENT_ID}&allow_signup=false`
)
}

try {
const data = await (
await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
body: JSON.stringify({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
code,
}),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
).json()

const accessToken = data.access_token
if (accessToken) {
const userInfo = await (
await fetch('https://api.github.com/user', {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
Authorization: `token ${accessToken}`,
Accept: 'application/json',
},
})
).json()

req.session.login = userInfo.login
req.session.email = userInfo.email
} else {
req.session.login = ''
req.session.email = ''
}
} catch (err) {
console.error(err)
return res.status(500).json({ error: 'Failed to auth.' })
}

return res.redirect('/')
}
48 changes: 48 additions & 0 deletions examples/with-fauna/pages/api/guestbook/[id].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import {
createGuestbookEntry,
getGuestbookEntry,
deleteGuestbookEntry,
} from '@/lib/fauna'
import session from '@/lib/session'

export default async function handler(req, res) {
session(req, res)

const { id } = req.query
const { login, email } = req.session
const entry = await getGuestbookEntry(id)

if (req.method === 'GET') {
const { email, ...restOfEntry } = entry

return res.json(restOfEntry)
}

if (req.method === 'DELETE') {
if (!login || login !== entry.created_by) {
return res.status(403).send('Unauthorized')
}

await deleteGuestbookEntry(id)
return res.status(204).json({})
}

if (req.method === 'PUT') {
if (!login || login !== entry.created_by) {
return res.status(403).send('Unauthorized')
}

const updated = {
id,
email,
updated_at: Date.now(),
body: (req.body.body || '').slice(0, 500),
created_by: login,
}

await createGuestbookEntry(updated)
return res.status(201).json(updated)
}

return res.send('Method not allowed.')
}
Loading