netlify-faunadb-example/README.md
2018-06-29 13:17:11 -07:00

4.9 KiB

Netlify + FaunaDB    

Example of using FaunaDB with Netlify functions

About this application

This application is using React for the frontend, Netlify Functions for API calls, and FaunaDB as the backing database.

faunadb netlify

Setup & Run Locally

  1. Clone down the repository

    git clone git@github.com:netlify/netlify-faunadb-example.git
    
  2. Install the dependencies

    npm install
    
  3. Bootstrap your FaunaDB table

    npm run bootstrap
    
  4. Set your Fauna API key value in your terminal enviroment

    You can create faunaDB keys here: https://dashboard.fauna.com/db/keys

    In your terminal run the following command:

    export FAUNADB_SECRET=YourFaunaDBKeyHere
    
  5. Run project locally

    npm start
    

TLDR; Quick Deploy

  1. Sign up for free FaunaDB account,
  2. Grab your FaunaDB API key
  3. Click the Deploy to Netlify Button

Deploy to Netlify

setup steps

Tutorial

Lets run through how to create Netlify functions and connect them to our frontend application.

  1. Step faunaDB
  2. Create /functions/todos-create.js

1. Setup FaunaDB

First things first, we need to setup a FaunaDB account and get our API key we will use to scaffold out our todos database.

Head over to https://app.fauna.com/sign-up to create a free Fauna Account.

  1. Sign up

    Sign up for Fauna

  2. Create a key

    Create a fauna key

  3. Name your key and create

    Name the fauna key and create

  4. Copy this API key for later use, or Deploy to Netlify Button and plugin this API key.

    Copy API key for future use

2. Create a function

Lambda functions have this signature:

exports.handler = (event, context, callback) => {
  // event has informatiom about the path, body, headers etc of the request
  console.log('event', event)
  // context has information about the lambda environment and user details
  console.log('context', context)
  // The callback ends the execution of the function and returns a reponse back to the caller
  return callback(null, {
    statusCode: 200,
    body: JSON.stringify({
      data: '⊂◉‿◉つ'
    })
  })
}

We are going to be using the FaunaDB sdk to call into our todos index.

/* Import faunaDB sdk */
import faunadb from 'faunadb'

const q = faunadb.query
const client = new faunadb.Client({
  secret: process.env.FAUNADB_SECRET
})

exports.handler = (event, context, callback) => {
  const data = JSON.parse(event.body)
  console.log("Function `todo-create` invoked", data)
  const todoItem = {
    data: data
  }
  /* construct the fauna query */
  return client.query(q.Create(q.Ref("classes/todos"), todoItem))
  .then((response) => {
    console.log("success", response)
    return callback(null, {
      statusCode: 200,
      body: JSON.stringify(response)
    })
  }).catch((error) => {
    console.log("error", error)
    return callback(null, {
      statusCode: 400,
      body: JSON.stringify(error)
    })
  })
}