如何从GCP云功能调用GCP数据存储?

时间:2017-11-10 18:58:06

标签: google-cloud-datastore google-cloud-functions gcp

以下是新GCP云功能提供的入门代码:

/**
 * 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);
  }
};

...和package.json:

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

寻找从这里调用DataStore的基本示例。

2 个答案:

答案 0 :(得分:1)

我不是Node.js用户,但根据文档,我认为一种方便的方法是使用Node.js Cloud Datastore Client Library。该页面的示例:

// 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);
  });

但您也可以查看Client Libraries Explained,因为它描述或指向其他选项的详细页面,其中一些可能更容易找到。< / p>

答案 1 :(得分:0)

您需要在package.json中包含DataStore依赖项

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