Robert Christian
Robert Christian

Reputation: 18300

How to call GCP Datastore from GCP Cloud Function?

Here's the starter code provided with a new GCP Cloud Function:

/**
 * Responds to any HTTP request that can provide a "message" field in the body.
 *
 * @param {!Object} req Cloud Function request context.
 * @param {!Object} res Cloud Function response context.
 */
exports.helloWorld = function helloWorld(req, res) {
  // Example input: {"message": "Hello!"}
  if (req.body.message === undefined) {
    // This is an error case, as "message" is required.
    res.status(400).send('No message defined!');
  } else {
    // Everything is okay.
    console.log(req.body.message);
    res.status(200).send('Success: ' + req.body.message);
  }
};

... and the package.json:

{
  "name": "sample-http",
  "version": "0.0.1"
}

Looking for a basic example of calling DataStore from here.

Upvotes: 3

Views: 1604

Answers (2)

Italo Pacheco
Italo Pacheco

Reputation: 29

you need to include the DataStore dependency in the package.json

{
  "name": "sample-http",
    "dependencies": {
    "@google-cloud/datastore": "1.3.4"
    },
  "version": "0.0.1"
}

Upvotes: 1

Dan Cornilescu
Dan Cornilescu

Reputation: 39814

I'm not a Node.js user, but based on the documentation I think one convenient way would be to use the Node.js Cloud Datastore Client Library. The example from that page:

// Imports the Google Cloud client library
const Datastore = require('@google-cloud/datastore');

// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Instantiates a client
const datastore = Datastore({
  projectId: projectId
});

// The kind for the new entity
const kind = 'Task';
// The name/ID for the new entity
const name = 'sampletask1';
// The Cloud Datastore key for the new entity
const taskKey = datastore.key([kind, name]);

// Prepares the new entity
const task = {
  key: taskKey,
  data: {
    description: 'Buy milk'
  }
};

// Saves the entity
datastore.save(task)
  .then(() => {
    console.log(`Saved ${task.key.name}: ${task.data.description}`);
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

But you may want to take a look at Client Libraries Explained as well, as it describes or points to detailed pages about other options as well, some of which one might find preferable.

Upvotes: 2

Related Questions