Skip to content

Instantly share code, notes, and snippets.

@pi0neerpat
Last active February 28, 2021 18:02
Show Gist options
  • Select an option

  • Save pi0neerpat/854cb578d6475c79b5797ec7c7e6dad4 to your computer and use it in GitHub Desktop.

Select an option

Save pi0neerpat/854cb578d6475c79b5797ec7c7e6dad4 to your computer and use it in GitHub Desktop.
5 minute REST API example in Redwood

Add to /api/db/schema.prisma

model Request {
  id        String   @id @default(uuid())
  createdAt DateTime @default(now())
  data String
  origin String
}

Throw this in /api/src/functions/request.js

const { PrismaClient } = require('@prisma/client')
const dotenv = require('dotenv')
dotenv.config()
const db = new PrismaClient()

exports.handler = async (event) => {
  console.log(event)

  // This is where we do our business logic
  await db.request.create({
    data: {
      data: event.body,
      origin: event.requestContext.identity.sourceIp,
    },
  })
  db.disconnect()

  // This is where we return our response
  return {
    statusCode: 200,
    body: event,
  }
}

Run these commands

yarn rw g scaffold request
yarn rw db save
yarn rw db up
yarn rw dev

Navigate to localhost:8911/request and you should see the details of your request printed on the screen.

It will also save info to the database. There are two ways to view this data:

  • Open localhost:8910/requests to see them in the frontend
  • Run yarn rw db studio to use a handy database admin/inspection tool
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment