Giter VIP home page Giter VIP logo

gcp-datastore-cloud-functions-realworld-example-app's Introduction

RealWorld Backend TravisCI Coverage Status Docs dependencies Status Known Vulnerabilities

Google Cloud Platform (Datastore + Cloud Functions) serverless codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld API Spec.

This codebase was created to demonstrate a fully fledged fullstack application built with Google Cloud Platform (Datastore + Cloud Functions) including CRUD operations, authentication, routing, pagination, and more.

We've gone to great lengths to adhere to community style guides & best practices.

For more information on how to this works with other frontends/backends, head over to the RealWorld repo.

How it works

Background

This codebase is meant to be deployed to Google Cloud Functions, a serverless environment which allows you to run NodeJS code in response to events like HTTP triggers scaling up and down elastically without the need for spinning up or maintaining servers.

Life of a Request

For every API call made, a new invocation of the top level function index.js occurs. It calls Router.js which parses the HTTP route and calls the appropriate handler in User.js or Article.js. The handler applies business logic and returns a response which is marshalled back to the caller by Cloud Functions.

For data persistence, Google Cloud Datastore is used which is a fully managed NoSQL database as a service. Cloud Datastore multitenancy is supported and can be leveraged by specifying a DATASTORE_NAMESPACE environment variable at runtime.

Datastore Schema

User

{ username: 'Julie_Stracke',
  password: '$2a$05$Unbla43FRv5Zb...',
  email: '[email protected]',
  image: '',
  bio: '',
  followers: [],
  following: [],
  [Symbol(KEY)]:
   Key {
     namespace: 'test-unit',
     name: 'Julie_Stracke',
     kind: 'User',
     path: [Getter] } }

Article

{ slug: 'In-enim-nur2bx',
  title: 'In enim',
  description: 'Suscipit voluptas minima...',
  body: 'Voluptates doloremque unde...',
  tagList: [ 'temporibus', 'quae', 'omnis', 'aut' ],
  createdAt: 1509036552780,
  updatedAt: 1509036552780,
  author: 'author_Paul_Heaney',
  favoritedBy: [],
  [Symbol(KEY)]:
   Key {
     namespace: 'test-unit',
     name: 'In-enim-nur2bx',
     kind: 'Article',
     path: [Getter] } }

Comment

{ body: 'Voluptatem dolorem repellat...',
  author: 'Wiegand_Hattie',
  createdAt: 1509036740596,
  updatedAt: 1509036740596,
  [Symbol(KEY)]:
   Key {
     namespace: 'test-unit',
     id: '5629499534213120',
     kind: 'Comment',
     parent:
      Key {
        namespace: 'test-unit',
        name: 'In-enim-nur2bx',
        kind: 'Article',
        path: [Getter] },
     path: [Getter] } }

Testing

Unit Tests

Unit tests live adjacent to source code as src/*.test.js and can be run by executing npm run test:unit. They use mocha as a test runner and istanbul/nyc for coverage.

API Tests

You can also run Postman based API tests by executing npm run test:api. These are run using the newman command line runner. The code is deployed locally to a Cloud Functions Local Emulator environment and tested. See run-api-tests.sh for details.

Linting

Code linting is enforced using eslint configured by .eslintrc.js. You can run the linter by executing npm run lint.

CI

Continuous integration is performed by TravisCI. See .travis.yml for details.

CD

If all tests pass, the code is automatically deployed to a Cloud Functions Endpoint. See deploy-to-cloud.sh for details.

Getting started

Setup Google Cloud Platform (GCP)

  • Signup for a Google Cloud Platform (GCP) Free Account here and create a new project
  • Setup Cloud Datastore for this project by following steps here
  • Install and setup gcloud CLI tool by following help here

Setup local development environment

Note: Node.js 8.0 or greater is required

  • Clone this repo
  • Create GCP Datastore indexes
gcloud datastore indexes create index.yaml
  • Create a service account and store the credentials as service-account-key.json in the repo root folder - DO NOT SHARE THIS FILE!
  • Ensure Datastore indexes are created before proceeding by checking here
  • Specify details about your GCP project,
export GOOGLE_APPLICATION_CREDENTIALS=service-account-key.json
export GCP_PROJECT_ID=<your-GCP-project-id>
  • Install dependencies
npm install
npx functions config set projectId $GCP_PROJECT_ID
  • Test
npm test

Deploy to Cloud Functions

npm run deploy

More details in deploy-to-cloud.sh.

gcp-datastore-cloud-functions-realworld-example-app's People

Contributors

akarandi avatar anishkny avatar dependabot-support avatar greenkeeper[bot] avatar oalsing avatar snyk-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gcp-datastore-cloud-functions-realworld-example-app's Issues

Local testing Video series

Would be nice to run this project locally. I am attempting to use the datastore emulator to do this with the functions framework and will report back.

I am also trying to use the functions-framework.

[question] Can we use the default service account?

You specify to

Create a service account and store the credentials as service-account-key.json in the repo root folder - DO NOT SHARE THIS FILE!

However, could we not just use the default service account for this tutorial?

error after npm test

Hello,

i have this error when try to run npm test

npm ERR! Failed at the @ test:unit script 'DATASTORE_NAMESPACE=test-unit-date +%s nyc mocha --opts .mochaopts ./src/.test.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! DATASTORE_NAMESPACE=test-unit-date +%s nyc mocha --opts .mochaopts ./src/
.test.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls
npm ERR! There is likely additional logging output above.

my node version is v6.11.5

we can help me to resolve ?

thanks

Guide for maintainers

My fork is starting to diverge in some fixes, and I'm not inclined to raise any more PRs as its getting more difficult to backport PRs and I haven't had comments on my PRs. Can you advise how the community can best help your excellent work in this project?

Running deploy gives: You do not currently have this command group installed

My console:

 gcp-datastore-cloud-functions-realworld-example-app git:(master) nd

> @ deploy /Users/nikos/WebstormProjects/gcp-datastore-cloud-functions-realworld-example-app
> ./deploy-to-cloud.sh

GCLOUD_BIN=gcloud
Deploying function...
You do not currently have this command group installed.  Using it 
requires the installation of components: [beta]


Your current Cloud SDK version is: 247.0.0
Installing components from version: 247.0.0

┌─────────────────────────────────────────────┐
│     These components will be installed.     │
├──────────────────────┬────────────┬─────────┤
│         Name         │  Version   │   Size  │
├──────────────────────┼────────────┼─────────┤
│ gcloud Beta Commands │ 2019.05.17 │ < 1 MiB │
└──────────────────────┴────────────┴─────────┘

For the latest full release notes, please visit:
  https://cloud.google.com/sdk/release_notes

Do you want to continue (Y/n)?          ^[[2B^[[2B

also see GoogleCloudPlatform/cloud-sdk-docker#74

Enable CORS

Hi,

I am trying to add CORS to this app and could really find the best way of having Access-Control-Allow-Origin as I am running the frontend on localhost:4200. All of my requests are being blocked in GCP.
I am trying to figure out where should I add the CORS. (Sorry, I am quite new to Nodejs and this may seem a silly question)

I was reading this
https://github.com/expressjs/cors
and then this
https://github.com/gothinkster/realworld/tree/master/api

which says I need to use OPTIONS to return correct headers.
I have this in my code in the Router.js

const headers = {}; headers["Access-Control-Allow-Origin"] = "*"; headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS"; headers["Access-Control-Max-Age"] = '86400'; // 24 hours headers["Access-Control-Allow-Headers"] = "Authorization, X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";

and also having a check

if (req.method === 'OPTIONS') { res.writeHead(200, headers); res.send(); }

But my app still throws the error

Failed to load https://my-app/api/tags: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Any help would really be appreciated.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.