Commit 581e3386 authored by fauna-brecht's avatar fauna-brecht Committed by Luis Alvarez D

with-graphql-faunadb (#9387)

* with-graphql-faunadb

* Use latest next

* Use node-fetch

* removed import to next/config

* Updated titles

* Lint fix

* Link to the schema
parent 59053974
# 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. [[Live demo](https://with-graphql-faunadb.now.sh/)].
## 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`](#use-create-next-app) or by [downloading the repository manually](#download-manually).
To use a live FaunaDB database, create one and import this example's `schema.gql` file using the FaunaDB console. Create a client secret, then paste it into `next.config.js`.
### Use `create-next-app`
Download [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) to bootstrap the example:
```
npm install -g create-next-app
create-next-app --example with-graphql-faunadb
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-graphql-faunadb
cd with-graphql-faunadb
```
### Run locally
Install, then run the development server:
```bash
npm install
now dev
```
Make sure to leave us a guestbook message in our [live demo](https://with-graphql-faunadb.now.sh/)! 😉
### Deploy
Deploy it to the cloud with [now](https://zeit.co/now)! [Install now](https://zeit.co/download) on your development machine before proceeding.
```bash
now
```
import {
footer,
footerContent,
footerColumn,
footerColumnFirst,
footerColumnFirstURL,
footerColumnList,
footerColumnListURL,
} from '../styles/footer.js'
export default props => (
<footer className={footer.className}>
<div className={footerContent.className}>
<div
className={`${footerColumn.className} ${footerColumnFirst.className}`}
>
<a href="https://fauna.com" target="_blank">
<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"
href="https://fauna.com/faunadb"
>
FaunaDB
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
href="https://fauna.com/pricing"
>
Pricing
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
href="https://fauna.com/resources"
>
Resources
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
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"
href="https://fauna.com/team"
>
Company
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
href="https://fauna.com/press"
>
Press
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
href="https://fauna.com/careers"
>
Careers
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
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"
href="https://community-invite.fauna.com/"
>
Community Slack
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
href="https://support.fauna.com/"
>
Support
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
href="https://dashboard.fauna.com/"
>
Login
</a>
</li>
<li>
<a
className={footerColumnListURL.className}
target="_blank"
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 props => (
<>
<div className={guestbookEntry.className}>
<div className={guestbookEntryUserDetail.className}>
<div className={guestbookEntryUserDetailAvatar.className}>
<a
target="_blank"
href={`https://twitter.com/${props.twitter_handle}/`}
>
<img
className={guestbookEntryUserDetailAvatarImg.className}
src={`https://avatars.io/twitter/${props.twitter_handle}/`}
/>
</a>
</div>
<a
className={guestbookEntryUserDetailBiolink.className}
target="_blank"
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 @zeithq'
)}&url=${encodeURIComponent(
'https://fauna.com'
)}&hashtags=graphql,nextjs
`}
target="_blank"
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 () => (
<>
<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 props => (
<>
<a href="https://fauna.com" target="_blank">
<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 React, { useState } from 'react'
import { createGuestbookEntry } from '../graphql/api'
import Header from './Header'
import GuestbookEntry from './GuestbookEntry'
import GuestbookEntryDivider from './GuestbookEntryDivider'
import {
hero,
heroForm,
heroFormFieldset,
heroFormTextArea,
heroFormTwitterInput,
heroFormSubmitButton,
heroEntries,
} from '../styles/hero'
export default props => {
let initEntries = []
try {
initEntries = props.initialEntries.slice(0)
} catch (err) {
console.log(`No initial entries`)
}
const [entries, setEntries] = useState(initEntries)
const [twitterHandle, setTwitterHandle] = useState('')
const [story, setStory] = useState('')
const [submitting, setSubmitting] = useState(false)
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={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}>
{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}
{hero.styles}
</>
)
}
import fetch from 'unfetch'
export default fetch
{
"browser": "./browser.js",
"main": "./server.js"
}
import fetch from 'node-fetch'
export default fetch
import fetch from '../fetch'
/**
|--------------------------------------------------
| 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 getGuestbookEntries = () => {
const query = `query Entries($size: Int) {
entries(_size: $size) {
data {
_id
_ts
twitter_handle
story
}
after
}
}`
const size = 100
return new Promise((resolve, reject) => {
fetch(process.env.faunaDbGraphQlEndpoint, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.faunaDbSecret}`,
'Content-type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
query,
variables: { size },
}),
})
.then(r => r.json())
.then(data => {
console.log(data)
resolve(data)
})
.catch(error => {
console.log(error)
reject(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
}
}`
return new Promise((resolve, reject) => {
fetch(process.env.faunaDbGraphQlEndpoint, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.faunaDbSecret}`,
'Content-type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
query,
variables: { twitterHandle, story },
}),
})
.then(r => r.json())
.then(data => {
console.log(data)
resolve(data)
})
.catch(error => {
console.log(error)
reject(error)
})
})
}
module.exports = {
env: {
/**
|--------------------------------------------------
| Set the client secret for your database here.
|
| Learn more about managing roles and creating private keys:
| https://docs.fauna.com/fauna/current/security/
|--------------------------------------------------
*/
faunaDbSecret: 'fnADcnWRUcACE_6uDSw05MspruDdWKk88ZSmsm2a',
faunaDbGraphQlEndpoint: 'https://graphql.fauna.com/graphql',
},
}
{
"name": "with-graphql-faunadb",
"version": "1.0.0",
"description": "",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"node-fetch": "2.6.0",
"react": "^16.10.2",
"react-dom": "^16.10.2",
"unfetch": "4.1.0"
}
}
import Head from 'next/head'
import { getGuestbookEntries } from '../graphql/api'
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 initialEntries={props.initialEntries} />
<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>
</>
)
}
Guestbook.getInitialProps = async function() {
const initialEntries = await getGuestbookEntries()
return {
initialEntries: initialEntries.data.entries.data.reverse(),
}
}
export default Guestbook
# A guestbook entry requires a twitter handle (!) and a story
# However, FaunaDB automatically adds two private values: _id and _ts
type GuestbookEntry {
twitter_handle: String!
story: String!
# _id: Generated by FaunaDB as each document's unique identifier
# _ts: Timestamp generated by FaunaDB upon object creation
}
# A query named 'entries' which returns an array of GuestbookEntry objects
# Implicit arguments: _size (count) and _cursor (location within the Index)
type Query {
entries: [GuestbookEntry]
}
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 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