Unverified Commit fe3f520d authored by Artyom Kurnikov's avatar Artyom Kurnikov Committed by GitHub

Update Fauna example with new guestbook (#27295)

Based on https://github.com/vercel/next.js/pull/26708

- Renames FaunaDB -> Fauna
- Moves to Tailwind instead of bespoke styling
- Use SWR instead of hand-rolled fetch wrapper
- List/Create API for Guestbook
- Preps for setting correct environment variables from Vercel integration
parent 63aeddbb
...@@ -32,3 +32,5 @@ yarn-error.log* ...@@ -32,3 +32,5 @@ yarn-error.log*
# vercel # vercel
.vercel .vercel
.idea
# 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
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-fauna with-fauna-app
# or
yarn create next-app --example with-fauna with-fauna-app
```
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 using yarn
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 an index and UDF**, in order to implement custom sorting (by createdAt field), we need to create a GraphQL resolver that uses [UDF](https://docs.fauna.com/fauna/current/api/graphql/functions?lang=javascript) based on sorting index.
- **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**, this is the token to be used in the app.
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.
### Run locally
Install packages, set up if needed, then run the development server:
```bash
npm install
# if you haven't run setup yet
npm run setup
npm run dev
# or using yarn
yarn
# if you haven't run setup yet
yarn setup
yarn dev
```
Your app should be up and running on [http://localhost:3000](http://localhost:3000)!
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>
)
}
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>
)
}
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>
)
}
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"],
"@/lib/*": ["lib/*"]
}
}
}
import { GraphQLClient, gql } from 'graphql-request'
const FAUNADB_GRAPHQL_ENDPOINT = 'https://graphql.fauna.com/graphql'
const FAUNADB_SECRET = process.env.FAUNADB_SECRET
const graphQLClient = new GraphQLClient(FAUNADB_GRAPHQL_ENDPOINT, {
headers: {
authorization: `Bearer ${FAUNADB_SECRET}`,
},
})
export const listGuestbookEntries = () => {
const query = gql`
query Entries($size: Int) {
entries(_size: $size) {
data {
_id
_ts
name
message
createdAt
}
}
}
`
return graphQLClient
.request(query, { size: 999 })
.then(({ entries: { data } }) => data)
}
export const createGuestbookEntry = (newEntry) => {
const mutation = gql`
mutation CreateGuestbookEntry($input: GuestbookEntryInput!) {
createGuestbookEntry(data: $input) {
_id
_ts
name
message
createdAt
}
}
`
return graphQLClient.request(mutation, { input: newEntry })
}
{
"name": "with-fauna",
"version": "1.0.0",
"license": "MIT",
"description": "Guestbook example with Next.js and Fauna.",
"scripts": {
"dev": "next",
"build": "yarn setup && next build",
"start": "next start",
"setup": "node ./scripts/setup.js"
},
"dependencies": {
"classnames": "2.3.1",
"date-fns": "2.23.0",
"faunadb": "4.3.0",
"graphql": "15.5.1",
"graphql-request": "3.5.0",
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"request": "2.88.2",
"swr": "0.5.6"
},
"devDependencies": {
"autoprefixer": "10.3.1",
"postcss": "8.3.6",
"prettier": "2.3.2",
"tailwindcss": "2.2.7",
"stream-to-promise": "3.0.0"
}
}
import { listGuestbookEntries, createGuestbookEntry } from '@/lib/fauna'
export default async function handler(req, res) {
const handlers = {
GET: async () => {
const entries = await listGuestbookEntries()
res.json(entries)
},
POST: async () => {
const {
body: { name, message },
} = req
const created = await createGuestbookEntry({
name,
message,
createdAt: new Date(),
})
res.json(created)
},
}
if (!handlers[req.method]) {
return res.status(405).end()
}
await handlers[req.method]()
}
import Head from 'next/head'
import { useState } from 'react'
import cn from 'classnames'
import formatDate from 'date-fns/format'
import useSWR, { mutate } from 'swr'
import 'tailwindcss/tailwind.css'
import { listGuestbookEntries } from '@/lib/fauna'
import SuccessMessage from '@/components/SuccessMessage'
import ErrorMessage from '@/components/ErrorMessage'
import LoadingSpinner from '@/components/LoadingSpinner'
const ENTRIES_PATH = '/api/entries'
const putEntry = (payload) =>
fetch(ENTRIES_PATH, {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json',
},
}).then((res) => (res.ok ? res.json() : Promise.reject(res)))
const useEntriesFlow = ({ initialEntries }) => {
const { data: entries } = useSWR(ENTRIES_PATH, {
initialData: initialEntries,
})
const onSubmit = async (payload) => {
await putEntry(payload)
await mutate(ENTRIES_PATH)
}
return {
entries,
onSubmit,
}
}
const AppHead = () => (
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charSet="utf-8" />
<link rel="shortcut icon" type="image/x-icon" href="/static/favicon.png" />
</Head>
)
const EntryItem = ({ entry }) => (
<div className="flex flex-col space-y-2">
<div className="prose dark:prose-dark w-full">{entry.message}</div>
<div className="flex items-center space-x-3">
<p className="text-sm text-gray-500">{entry.name}</p>
<span className="text-gray-200 dark:text-gray-800">/</span>
<p className="text-sm text-gray-400 dark:text-gray-600">
{formatDate(new Date(entry.createdAt), "d MMM yyyy 'at' h:mm bb")}
</p>
</div>
</div>
)
const EntryForm = ({ onSubmit: onSubmitProp }) => {
const initial = {
name: '',
message: '',
}
const [values, setValues] = useState(initial)
const [formState, setFormState] = useState('initial')
const isSubmitting = formState === 'submitting'
const onSubmit = (ev) => {
ev.preventDefault()
setFormState('submitting')
onSubmitProp(values)
.then(() => {
setValues(initial)
setFormState('submitted')
})
.catch(() => {
setFormState('failed')
})
}
const makeOnChange = (fieldName) => ({ target: { value } }) =>
setValues({
...values,
[fieldName]: value,
})
const inputClasses = cn(
'block py-2 bg-white dark:bg-gray-800',
'rounded-md border-gray-300 focus:ring-blue-500',
'focus:border-blue-500 text-gray-900 dark:text-gray-100'
)
return (
<>
<form className="flex relative my-4" onSubmit={onSubmit}>
<input
required
className={cn(inputClasses, 'w-1/3 mr-2 px-4')}
aria-label="Your name"
placeholder="Your name..."
value={values.name}
onChange={makeOnChange('name')}
/>
<input
required
className={cn(inputClasses, 'pl-4 pr-32 flex-grow')}
aria-label="Your message"
placeholder="Your message..."
value={values.message}
onChange={makeOnChange('message')}
/>
<button
className={cn(
'flex items-center justify-center',
'absolute right-1 top-1 px-4 font-bold h-8',
'bg-gray-100 dark:bg-gray-700 text-gray-900',
'dark:text-gray-100 rounded w-28'
)}
type="submit"
disabled={isSubmitting}
>
{isSubmitting ? <LoadingSpinner /> : 'Sign'}
</button>
</form>
{{
failed: () => <ErrorMessage>Something went wrong. :(</ErrorMessage>,
submitted: () => (
<SuccessMessage>Thanks for signing the guestbook.</SuccessMessage>
),
}[formState]?.()}
</>
)
}
const Guestbook = ({ initialEntries }) => {
const { entries, onSubmit } = useEntriesFlow({
initialEntries,
})
return (
<main className="max-w-4xl mx-auto p-4">
<AppHead />
<div
className={cn(
'border border-blue-200 rounded p-6',
'my-4 w-full dark:border-gray-800 bg-blue-50',
'dark:bg-blue-opaque'
)}
>
<h5
className={cn(
'text-lg md:text-xl font-bold',
'text-gray-900 dark:text-gray-100'
)}
>
Sign the Guestbook
</h5>
<p className="my-1 text-gray-800 dark:text-gray-200">
Share a message for a future visitor.
</p>
<EntryForm onSubmit={onSubmit} />
</div>
<div className="mt-4 space-y-8 px-2">
{entries?.map((entry) => (
<EntryItem key={entry._id} entry={entry} />
))}
</div>
</main>
)
}
export const getStaticProps = async () => ({
props: {
initialEntries: await listGuestbookEntries(),
},
})
export default Guestbook
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
# A guestbook entry requires a twitter handle (!) and a story
# However, FaunaDB automatically adds two private values: _id and _ts
type GuestbookEntry { type GuestbookEntry {
twitter_handle: String! name: String!
story: String! message: String!
# _id: Generated by FaunaDB as each document's unique identifier createdAt: Time!
# _ts: Timestamp generated by FaunaDB upon object creation # _id: Generated by Fauna as each document's unique identifier
# _ts: Timestamp generated by Fauna upon object updating
} }
# A query named 'entries' which returns an array of GuestbookEntry objects # A query named 'entries' which returns an array of GuestbookEntry objects
# Implicit arguments: _size (count) and _cursor (location within the Index) # Implicit arguments: _size (count) and _cursor (location within the Index)
type Query { type Query {
entries: [GuestbookEntry] entries: [GuestbookEntry!]
@resolver(name: "listLatestEntries", paginated: true)
} }
// This script sets up the database to be used for this example application.
// Look at the code to see what is behind the magic
const fs = require('fs')
const readline = require('readline')
const request = require('request')
const { Client, query: Q } = require('faunadb')
const streamToPromise = require('stream-to-promise')
const FAUNA_ADMIN_KEY = process.env.FAUNA_ADMIN_KEY
const MakeLatestEntriesIndex = () =>
Q.CreateIndex({
name: 'latestEntries',
source: Q.Collection('GuestbookEntry'),
values: [
{
field: ['data', 'createdAt'],
reverse: true,
},
{
field: 'ref',
},
],
})
const MakeListLatestEntriesUdf = () =>
Q.Update(Q.Function('listLatestEntries'), {
// https://docs.fauna.com/fauna/current/api/graphql/functions?lang=javascript#paginated
body: Q.Query(
Q.Lambda(
['size', 'after', 'before'],
Q.Let(
{
match: Q.Match(Q.Index('latestEntries')),
page: Q.If(
Q.Equals(Q.Var('before'), null),
Q.If(
Q.Equals(Q.Var('after'), null),
Q.Paginate(Q.Var('match'), {
size: Q.Var('size'),
}),
Q.Paginate(Q.Var('match'), {
size: Q.Var('size'),
after: Q.Var('after'),
})
),
Q.Paginate(Q.Var('match'), {
size: Q.Var('size'),
before: Q.Var('before'),
})
),
},
Q.Map(Q.Var('page'), Q.Lambda(['_', 'ref'], Q.Get(Q.Var('ref'))))
)
)
),
})
const MakeGuestbookRole = () =>
Q.CreateRole({
name: 'GuestbookRole',
privileges: [
{
resource: Q.Collection('GuestbookEntry'),
actions: {
read: true,
write: true,
create: true,
},
},
{
resource: Q.Index('latestEntries'),
actions: {
read: true,
},
},
{
resource: Q.Function('listLatestEntries'),
actions: {
call: true,
},
},
],
})
const MakeGuestbookKey = () =>
Q.CreateKey({
role: Q.Role('GuestbookRole'),
})
const askAdminKey = () => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
return new Promise((resolve) => {
rl.question('Please provide the Fauna admin key:\n', (res) => {
rl.close()
resolve(res)
})
})
}
const importSchema = (adminKey) =>
streamToPromise(
fs.createReadStream('./schema.gql').pipe(
request.post({
model: 'merge',
uri: 'https://graphql.fauna.com/import',
headers: {
Authorization: `Bearer ${adminKey}`,
},
})
)
).then(String)
const findImportError = (msg) => {
switch (true) {
case msg.startsWith('Invalid authorization header'):
return 'You need to provide a secret, closing. Try again'
case msg.startsWith('Invalid database secret'):
return 'The secret you have provided is not valid, closing. Try again'
case !msg.includes('success'):
return msg
default:
return null
}
}
const main = async () => {
const adminKey = FAUNA_ADMIN_KEY || (await askAdminKey())
const importMsg = await importSchema(adminKey)
const importErrorMsg = findImportError(importMsg)
if (importErrorMsg) {
return Promise.reject(new Error(importErrorMsg))
}
console.log('1. Successfully imported schema')
const client = new Client({ secret: adminKey })
for (const Make of [
MakeLatestEntriesIndex,
MakeListLatestEntriesUdf,
MakeGuestbookRole,
]) {
await client.query(Make())
}
const { secret } = await client.query(MakeGuestbookKey())
console.log('2. Created Fauna resources')
await fs.promises.writeFile('.env.local', `FAUNADB_SECRET=${secret}\n`)
console.log('3. Created .env.local file with secret')
}
main().catch((err) => {
console.error(err)
process.exit(1)
})
module.exports = {
mode: 'jit',
purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
NEXT_PUBLIC_FAUNADB_SECRET=<replace-with-generated-client-secret>
NEXT_PUBLIC_FAUNADB_GRAPHQL_ENDPOINT=https://graphql.fauna.com/graphql
\ No newline at end of file
# FaunaDB Graphql Starter Example -- The FaunaDB Guestbook # FaunaDB Graphql Starter Example -- The FaunaDB Guestbook
This simple Guestbook SPA example shows you how to use [FaunaDB's GraphQL endpoint](https://docs.fauna.com/fauna/current/api/graphql/) in your Next.js project. This sample application has been moved to [another folder](https://github.com/vercel/next.js/tree/canary/examples/with-fauna).
## 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-graphql-faunadb&project-name=my-nextjs-guestbook&repository-name=my-nextjs-guestbook&env=NEXT_PUBLIC_FAUNADB_SECRET,NEXT_PUBLIC_FAUNADB_GRAPHQL_ENDPOINT&envDescription=Client%20secret%20and%20GraphQL%20endpoint%20needed%20for%20communicating%20with%20the%20live%20Fauna%20database&demo-title=Next.js%20Fauna%20Guestbook%20App&demo-description=A%20simple%20guestbook%20application%20built%20with%20Next.js%20and%20Fauna&demo-url=https%3A%2F%2Fnextjs-guestbook.vercel.app%2F)
## Why FaunaDB
By importing a `.gql` or `.graphql` schema into FaunaDB ([see our sample schema file](./schema.gql)), FaunaDB 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 FaunaDB 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 FaunaDB, FaunaDB 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**, FaunaDB 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-faunadb with-graphql-faunadb-app
# or
yarn create next-app --example with-graphql-faunadb with-graphql-faunadb-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)!
### Deploy
[![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-graphql-faunadb&project-name=my-nextjs-guestbook&repository-name=my-nextjs-guestbook&env=NEXT_PUBLIC_FAUNADB_SECRET,NEXT_PUBLIC_FAUNADB_GRAPHQL_ENDPOINT&envDescription=Client%20secret%20and%20GraphQL%20endpoint%20needed%20for%20communicating%20with%20the%20live%20Fauna%20database&demo-title=Next.js%20Fauna%20Guestbook%20App&demo-description=A%20simple%20guestbook%20application%20built%20with%20Next.js%20and%20Fauna&demo-url=https%3A%2F%2Fnextjs-guestbook.vercel.app%2F)
import {
footer,
footerContent,
footerColumn,
footerColumnFirst,
footerColumnFirstURL,
footerColumnList,
footerColumnListURL,
} from '../styles/footer.js'
export default function Footer(props) {
return (
<footer className={footer.className}>
<div className={footerContent.className}>
<div
className={`${footerColumn.className} ${footerColumnFirst.className}`}
>
<a href="https://fauna.com" target="_blank" rel="noopener noreferrer">
<img
src="/static/fauna-logo-white.png"
height="35px"
width="auto"
/>
</a>
<p>
744 Montgomery Street
<br />
Suite 200
<br />
San Francisco, CA 94111
<br />
<a
href="mailto:info@fauna.com"
className={footerColumnFirstURL.className}
>
info@fauna.com
</a>
</p>
</div>
<div className={footerColumn.className}>
Fauna
<ul className={footerColumnList.className}>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
rel="noopener noreferrer"
href="https://fauna.com/faunadb"
>
FaunaDB
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
rel="noopener noreferrer"
href="https://fauna.com/pricing"
>
Pricing
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
rel="noopener noreferrer"
href="https://fauna.com/resources"
>
Resources
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
rel="noopener noreferrer"
href="https://fauna.com/blog"
>
Blog
</a>
</li>
</ul>
</div>
<div className={footerColumn.className}>
About
<ul className={footerColumnList.className}>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
rel="noopener noreferrer"
href="https://fauna.com/team"
>
Company
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
rel="noopener noreferrer"
href="https://fauna.com/press"
>
Press
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
rel="noopener noreferrer"
href="https://fauna.com/careers"
>
Careers
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
rel="noopener noreferrer"
href="http://www2.fauna.com/contact-us"
>
Contact
</a>
</li>
</ul>
</div>
<div className={footerColumn.className}>
Quicklinks
<ul className={footerColumnList.className}>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
rel="noopener noreferrer"
href="https://community-invite.fauna.com/"
>
Community Slack
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
rel="noopener noreferrer"
href="https://support.fauna.com/"
>
Support
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
rel="noopener noreferrer"
href="https://dashboard.fauna.com/"
>
Login
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
rel="noopener noreferrer"
href="https://dashboard.fauna.com/accounts/register"
>
Signup
</a>
</li>
</ul>
</div>
</div>
{footerColumnListURL.styles}
{footerColumnList.styles}
{footerColumnFirstURL.styles}
{footerColumnFirst.styles}
{footerColumn.styles}
{footerContent.styles}
{footer.styles}
</footer>
)
}
import {
guestbookEntry,
guestbookEntryUserDetail,
guestbookEntryUserDetailAvatar,
guestbookEntryUserDetailAvatarImg,
guestbookEntryUserDetailTimestamp,
guestbookEntryUserDetailBiolink,
guestbookEntryStory,
guestbookEntryShare,
guestbookEntryShareTwitterButton,
guestbookEntryShareTwitterButtonLogo1,
guestbookEntryShareTwitterButtonLogo2,
} from '../styles/guestbookentry'
export default function GuestbookEntry(props) {
return (
<>
<div className={guestbookEntry.className}>
<div className={guestbookEntryUserDetail.className}>
<div className={guestbookEntryUserDetailAvatar.className}>
<a
target="_blank"
rel="noopener noreferrer"
href={`https://twitter.com/${props.twitter_handle}/`}
>
<img
className={guestbookEntryUserDetailAvatarImg.className}
src={`https://twitter-avatar.vercel.app/${props.twitter_handle}/`}
/>
</a>
</div>
<a
className={guestbookEntryUserDetailBiolink.className}
target="_blank"
rel="noopener noreferrer"
href={`https://twitter.com/${props.twitter_handle}/`}
>
{props.twitter_handle}
</a>
<span className={guestbookEntryUserDetailTimestamp.className}>
{props.date.toDateString()}
</span>
</div>
<div className={guestbookEntryStory.className}>{props.story}</div>
</div>
<div className={guestbookEntryShare.className}>
<a
href={`http://twitter.com/share?text=${encodeURIComponent(
props.story + ' @faunadb @vercel'
)}&url=${encodeURIComponent(
'https://fauna.com'
)}&hashtags=graphql,nextjs`}
target="_blank"
rel="noopener noreferrer"
className={guestbookEntryShareTwitterButton.className}
>
<img
src="/static/twitter_icon_black.png"
className={guestbookEntryShareTwitterButtonLogo1.className}
/>
<img
className={guestbookEntryShareTwitterButtonLogo2.className}
src="/static/twitter_icon_blue.png"
/>
</a>
</div>
{guestbookEntry.styles}
{guestbookEntryShare.styles}
{guestbookEntryShareTwitterButton.styles}
{guestbookEntryShareTwitterButtonLogo1.styles}
{guestbookEntryShareTwitterButtonLogo2.styles}
{guestbookEntryStory.styles}
{guestbookEntryUserDetail.styles}
{guestbookEntryUserDetailAvatar.styles}
{guestbookEntryUserDetailAvatarImg.styles}
{guestbookEntryUserDetailBiolink.styles}
{guestbookEntryUserDetailTimestamp.styles}
</>
)
}
export default function GuestbookEntryDivider() {
return (
<>
<hr />
<style jsx>{`
hr {
display: block;
margin-left: auto;
margin-right: auto;
margin-bottom: 30px;
height: 1px;
width: 80%;
border-radius: 20px;
border-color: rgba(50, 63, 203);
opacity: 0.5;
}
`}</style>
</>
)
}
import { headerBanner, headerTitle } from '../styles/header'
export default function Header(props) {
return (
<>
<a href="https://fauna.com" target="_blank" rel="noopener noreferrer">
<img
className={headerBanner.className}
src="/static/fauna-logo-blue.png"
height="35px"
width="auto"
/>
</a>
<h1 className={headerTitle.className}>Guestbook</h1>
{headerBanner.styles}
{headerTitle.styles}
</>
)
}
import { useState, useEffect } from 'react'
import { useGuestbookEntries, createGuestbookEntry } from '../graphql/api'
import Header from './Header'
import GuestbookEntry from './GuestbookEntry'
import GuestbookEntryDivider from './GuestbookEntryDivider'
import {
hero,
heroContainer,
heroForm,
heroFormFieldset,
heroFormTextArea,
heroFormTwitterInput,
heroFormSubmitButton,
heroEntries,
} from '../styles/hero'
function getEntries(data) {
return data ? data.entries.data.reverse() : []
}
export default function Hero(props) {
const { data, errorMessage } = useGuestbookEntries()
const [entries, setEntries] = useState([])
const [twitterHandle, setTwitterHandle] = useState('')
const [story, setStory] = useState('')
const [submitting, setSubmitting] = useState(false)
useEffect(() => {
if (!entries.length) {
setEntries(getEntries(data))
}
}, [data, entries.length])
function handleSubmit(event) {
event.preventDefault()
if (twitterHandle.trim().length === 0) {
alert('Please provide a valid twitter handle :)')
return
}
if (story.trim().length === 0) {
alert('No favorite memory? This cannot be!')
return
}
setSubmitting(true)
createGuestbookEntry(twitterHandle, story)
.then((data) => {
entries.unshift(data.data.createGuestbookEntry)
setTwitterHandle('')
setStory('')
setEntries(entries)
setSubmitting(false)
})
.catch((error) => {
console.log(`boo :( ${error}`)
alert('🤷‍♀️')
setSubmitting(false)
})
}
function handleStoryChange(event) {
setStory(event.target.value)
}
function handleTwitterChange(event) {
setTwitterHandle(event.target.value.replace('@', ''))
}
return (
<div className={heroContainer.className}>
<div className={hero.className}>
<Header />
<form className={heroForm.className} onSubmit={handleSubmit}>
<fieldset
className={heroFormFieldset.className}
disabled={submitting && 'disabled'}
>
<textarea
className={heroFormTextArea.className}
rows="5"
cols="50"
name="story"
placeholder="What is your favorite memory as a developer?"
onChange={handleStoryChange}
value={story}
/>
<input
className={heroFormTwitterInput.className}
type="text"
placeholder="twitter handle (no '@')"
onChange={handleTwitterChange}
value={twitterHandle}
/>
<input
className={heroFormSubmitButton.className}
type="submit"
value="Submit"
/>
</fieldset>
</form>
</div>
<div className={heroEntries.className}>
{errorMessage ? (
<p>{errorMessage}</p>
) : !data ? (
<p>Loading entries...</p>
) : (
entries.map((entry, index, allEntries) => {
const date = new Date(entry._ts / 1000)
return (
<div key={entry._id}>
<GuestbookEntry
twitter_handle={entry.twitter_handle}
story={entry.story}
date={date}
/>
{index < allEntries.length - 1 && <GuestbookEntryDivider />}
</div>
)
})
)}
</div>
{heroEntries.styles}
{heroFormSubmitButton.styles}
{heroFormTwitterInput.styles}
{heroFormTextArea.styles}
{heroFormFieldset.styles}
{heroForm.styles}
{heroContainer.styles}
{hero.styles}
</div>
)
}
import useFetch from '../lib/useFetch'
function getData(data) {
if (!data || data.errors) return null
return data.data
}
function getErrorMessage(error, data) {
if (error) return error.message
if (data && data.errors) {
return data.errors[0].message
}
return null
}
/**
|--------------------------------------------------
| This GraphQL query returns an array of Guestbook
| entries complete with both the provided and implicit
| data attributes.
|
| Learn more about GraphQL: https://graphql.org/learn/
|--------------------------------------------------
*/
export const useGuestbookEntries = () => {
const query = `query Entries($size: Int) {
entries(_size: $size) {
data {
_id
_ts
twitter_handle
story
}
after
}
}`
const size = 100
const { data, error } = useFetch(
process.env.NEXT_PUBLIC_FAUNADB_GRAPHQL_ENDPOINT,
{
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.NEXT_PUBLIC_FAUNADB_SECRET}`,
'Content-type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
query,
variables: { size },
}),
}
)
return {
data: getData(data),
errorMessage: getErrorMessage(error, data),
error,
}
}
/**
|--------------------------------------------------
| This GraphQL mutation creates a new GuestbookEntry
| with the requisite twitter handle and story arguments.
|
| It returns the stored data and includes the unique
| identifier (_id) as well as _ts (time created).
|
| The guestbook uses the _id value as the unique key
| and the _ts value to sort and display the date of
| publication.
|
| Learn more about GraphQL mutations: https://graphql.org/learn/queries/#mutations
|--------------------------------------------------
*/
export const createGuestbookEntry = async (twitterHandle, story) => {
const query = `mutation CreateGuestbookEntry($twitterHandle: String!, $story: String!) {
createGuestbookEntry(data: {
twitter_handle: $twitterHandle,
story: $story
}) {
_id
_ts
twitter_handle
story
}
}`
const res = await fetch(process.env.NEXT_PUBLIC_FAUNADB_GRAPHQL_ENDPOINT, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.NEXT_PUBLIC_FAUNADB_SECRET}`,
'Content-type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
query,
variables: { twitterHandle, story },
}),
})
const data = await res.json()
return data
}
import { useState, useEffect } from 'react'
export default function useFetch(url, options) {
const [data, setData] = useState(null)
const [error, setError] = useState(null)
useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url, options)
const json = await res.json()
setData(json)
} catch (error) {
setError(error)
}
}
fetchData()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [url])
return { data, error }
}
{
"private": true,
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"setup": "node ./scripts/setup.js"
},
"dependencies": {
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"faunadb": "2.11.1",
"request": "2.88.0",
"stream-to-promise": "2.2.0"
},
"license": "MIT"
}
import Head from 'next/head'
import Footer from '../components/Footer'
import Hero from '../components/Hero'
const Guestbook = (props) => {
return (
<>
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charSet="utf-8" />
<link
rel="shortcut icon"
type="image/x-icon"
href="/static/favicon.png"
/>
</Head>
<style jsx global>{`
body {
margin: 0px;
padding: 0px;
}
`}</style>
<div>
<Hero />
<Footer />
</div>
<style jsx>{`
div {
display: flex;
margin-left: auto;
margin-right: auto;
font-family: sans-serif, sans;
flex-direction: column;
align-items: center;
}
`}</style>
</>
)
}
export default Guestbook
// This script sets up the database to be used for this example application.
// Look at the code to see what is behind the magic
const faunadb = require('faunadb')
const q = faunadb.query
const request = require('request')
const fs = require('fs')
const streamToPromise = require('stream-to-promise')
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
})
// In order to set up a database, we need an admin key, so let's ask the user for a key.
readline.question(`Please provide the FaunaDB admin key\n`, (adminKey) => {
// A graphql schema can be imported in override or merge mode: 'https://docs.fauna.com/fauna/current/api/graphql/endpoints#import'
const options = {
model: 'merge',
uri: 'https://graphql.fauna.com/import',
headers: { Authorization: `Bearer ${adminKey}` },
}
const stream = fs.createReadStream('./schema.gql').pipe(request.post(options))
streamToPromise(stream)
.then((res) => {
const readableResult = res.toString()
if (readableResult.startsWith('Invalid authorization header')) {
console.error('You need to provide a secret, closing. Try again')
return readline.close()
} else if (readableResult.startsWith('Invalid database secret')) {
console.error(
'The secret you have provided is not valid, closing. Try again'
)
return readline.close()
} else if (readableResult.includes('success')) {
console.log('1. Successfully imported schema')
return readline.close()
}
})
.catch((err) => {
console.error(err)
console.error(`Could not import schema, closing`)
})
.then((res) => {
// The GraphQL schema is important, this means that we now have a GuestbookEntry Collection and an entries index.
// Then we create a token that can only read and write to that index and collection
var client = new faunadb.Client({ secret: adminKey })
return client
.query(
q.CreateRole({
name: 'GuestbookRole',
privileges: [
{
resource: q.Collection('GuestbookEntry'),
actions: { read: true, write: true, create: true },
},
{
resource: q.Index('entries'),
actions: { read: true },
},
],
})
)
.then((res) => {
console.log(
'2. Successfully created role to read and write guestbook entries'
)
})
.catch((err) => {
if (err.toString().includes('instance already exists')) {
console.log('2. Role already exists.')
} else {
throw err
}
})
})
.catch((err) => {
console.error(err)
console.error(`Failed to create role, closing`)
})
.then((res) => {
// The GraphQL schema is important, this means that we now have a GuestbookEntry Collection and an entries index.
// Then we create a token that can only read and write to that index and collection
var client = new faunadb.Client({ secret: adminKey })
return client
.query(
q.CreateKey({
role: q.Role('GuestbookRole'),
})
)
.then((res) => {
console.log('3. Created key to use in client')
const envFile =
'NEXT_PUBLIC_FAUNADB_SECRET=' +
res.secret +
'\n' +
'NEXT_PUBLIC_FAUNADB_GRAPHQL_ENDPOINT=https://graphql.fauna.com/graphql'
fs.writeFile('.env.local', envFile, (err) => {
if (err) {
console.error(
'Failed to create .env.local file. Copy the .env.local.example file and provide the secret shown below:'
)
console.log(res.secret)
} else {
console.log('4. Created .env.local file with secret\n')
fs.readFile('.env.local', (err, data) => {
if (!err) {
console.log('.env.local:\n')
console.log(data.toString('utf-8'))
}
})
}
})
})
})
.catch((err) => {
console.error(err)
console.error(`Failed to create key, closing`)
})
})
import css from 'styled-jsx/css'
export const footer = css.resolve`
flex-grow: 1;
flex-shrink: 0;
flex-basis: 140px;
width: 100%;
background-color: rgba(50, 63, 203);
padding-top: 20px;
padding-bottom: 20px;
display: flex;
flex-direction: row;
align-items: center;
`
export const footerContent = css.resolve`
div {
margin: auto;
display: flex;
flex-direction: row;
align-items: center;
color: white !important;
max-width: 800px;
width: 100%;
}
`
export const footerColumn = css.resolve`
div {
flex-basis: 25%;
padding-left: 70px;
}
`
export const footerColumnFirst = css.resolve`
div {
font-size: 60% !important;
}
`
export const footerColumnFirstURL = css.resolve`
a {
color: white !important;
}
`
export const footerColumnList = css.resolve`
ul {
list-style-type: none;
padding: 0;
}
`
export const footerColumnListURL = css.resolve`
a {
color: white;
text-decoration: none;
transition: color 200ms ease-in-out;
color: rgba(255, 255, 255, 0.5);
}
a:hover {
color: white;
}
`
import css from 'styled-jsx/css'
export const guestbookEntry = css.resolve`
div {
width: 100%;
display: inline-flex;
flex-direction: row;
align-items: center;
margin-bottom: 30px;
}
`
export const guestbookEntryUserDetail = css.resolve`
div {
flex-shrink: 0;
flex-basis: 30%;
text-align: center;
}
`
export const guestbookEntryUserDetailAvatar = css.resolve`
div {
display: inline-block;
position: relative;
margin-bottom: 5px;
width: 70px;
height: 70px;
}
`
export const guestbookEntryUserDetailAvatarImg = css.resolve`
img {
position: absolute;
width: 100%;
height: 100%;
left: 0;
right: 0;
top: 0;
bottom: 0;
border-radius: 50%;
border: 2px solid rgba(50, 63, 203, 0.5);
opacity: 0.75;
transition: all 200ms ease-in-out;
}
img:hover {
opacity: 1;
border-color: rgba(50, 63, 203);
}
`
export const guestbookEntryUserDetailBiolink = css.resolve`
a {
display: block;
margin-bottom: 5px;
text-decoration: none;
color: rgba(50, 63, 203, 0.5);
font-size: 70%;
transition: color 200ms ease-in-out;
}
a:hover {
color: rgba(50, 63, 203);
}
`
export const guestbookEntryUserDetailTimestamp = css.resolve`
span {
display: block;
font-size: 70%;
font-weight: 200;
color: gray;
}
`
export const guestbookEntryStory = css.resolve`
div {
flex-shrink: 0;
flex-basis: 60%;
text-align: left;
padding-right: 15px;
white-space: pre-wrap;
}
`
export const guestbookEntryShare = css.resolve`
div {
margin-bottom: 30px;
}
`
export const guestbookEntryShareTwitterButton = css.resolve`
a {
display: inline-block;
width: 20px;
height: 20px;
position: relative;
}
`
export const guestbookEntryShareTwitterButtonLogo1 = css.resolve`
img {
position: absolute;
width: 100%;
height: 100%;
opacity: 0.5;
}
`
export const guestbookEntryShareTwitterButtonLogo2 = css.resolve`
img {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 200ms ease-in-out;
}
img:hover {
opacity: 1;
}
`
import css from 'styled-jsx/css'
export const headerBanner = css.resolve`
img {
padding-top: 15px;
}
`
export const headerTitle = css.resolve`
h1 {
font-size: 300%;
font-weight: normal;
margin: 15px 0;
}
`
import css from 'styled-jsx/css'
export const heroContainer = css.resolve`
div {
width: 100%;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
}
`
export const hero = css.resolve`
div {
width: 70%;
max-width: 700px;
text-align: center;
flex-basis: 30%;
}
`
export const heroForm = css.resolve`
form {
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
text-align: left;
width: 50%;
margin-bottom: 60px;
}
`
export const heroFormFieldset = css.resolve`
fieldset {
outline: none;
border: none;
}
`
export const heroFormTextArea = css.resolve`
textarea {
display: block;
width: 100%;
margin-bottom: 20px;
resize: none;
padding: 5px;
border-radius: 5px;
border: 1.2px solid rgba(50, 63, 203, 0.5);
transition: border 200ms ease-in-out;
box-sizing: border-box;
font-family: sans-serif;
}
textarea:hover,
textarea:focus {
outline: none !important;
border: 1.2px solid rgba(50, 63, 203);
}
`
export const heroFormTwitterInput = css.resolve`
input {
display: inline-block;
width: 45%;
padding: 5px;
border-radius: 5px;
border: 1.2px solid rgba(50, 63, 203, 0.5);
transition: border 200ms ease-in-out;
}
input:hover,
input:focus {
outline: none !important;
border: 1.2px solid rgba(50, 63, 203);
}
`
export const heroFormSubmitButton = css.resolve`
input {
width: 45%;
border-radius: 5px;
padding: 5px;
float: right;
background-color: rgba(50, 63, 203);
color: white;
font-weight: bold;
border: 1.2px solid rgba(50, 63, 203, 0.5);
}
input:hover {
cursor: pointer;
}
`
export const heroEntries = css.resolve`
div {
flex-grow: 0;
flex-shrink: 10;
flex-basis: 60%;
overflow-y: auto;
overflow-x: hidden;
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
width: 56%;
max-width: 800px;
text-align: center;
}
div::-webkit-scrollbar {
width: 2px;
}
div::-webkit-scrollbar-thumb {
background: rgba(50, 63, 203, 0.5);
}
`
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