Чтобы запустить показанный вами пример, следуйте инструкциям в документации :
- Загрузите файл учетных данных
JSON
и создайте переменную среды, которая указывает на этот файл:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/credential-file.json"
- Скопируйте код в файл 1011 * и запустите
node sample.js
.
С другой стороны, если вы хотите развернуть приложение nodejs
, вам потребуется express.js
или любая другая инфраструктура.
Я сделал следующее с помощью express.js
:
Я завернул ваш код в функцию под названием saveEntity(datastore)
Затем я добавил express.js в приложение, как в примере приложения nodejs , и оттуда я вызвал saveEntity (datastore):
app.get('/', (req, res) => {
saveEntity(datastore);
res.status(200).send("Entity saved").end();
});
// [START listen]
const PORT = process.env.PORT || 8080;
app.listen(process.env.PORT || 8080, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
// [END listen]
// [END app]
module.exports = app;
Полный результат таков:
// Imports the Google Cloud client library
const Datastore = require('@google-cloud/datastore');
//Needed to create the node app
const express = require('express')
const app = express();
// Your Google Cloud Platform project ID
const projectId = 'my-project-id';
// Creates a client
const datastore = new Datastore({
projectId: projectId,
});
function saveEntity(datastore){
// The kind for the new entity
const kind = 'JulyTask';
// The name/ID for the new entity
const name = 'sampletask1';
// The Cloud Datastore key for the new entity
const taskKey = datastore.key([kind, name]);
// Creates entity data
const task = {
name: 'Learn something',
status: 'In progress',
description: 'Friday 6 July'
}
//With the data and the key, create the entity
const entity = {
key: taskKey,
data: task
}
// Saves the entity
datastore
.upsert(entity)
.then(() => {
console.log('Saved:\n' + JSON.stringify(entity));
return true;
})
.catch(err => {
console.error('ERROR:', err);
return false;
});
}
app.get('/', (req, res) => {
saveEntity(datastore);
res.status(200).send("Entity saved").end();
});
// [START listen]
const PORT = process.env.PORT || 8080;
app.listen(process.env.PORT || 8080, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
// [END listen]
// [END app]
module.exports = app;
package.json
:
{
"name": "first-application",
"version": "1.0.0",
"description": "First program using cloud datastore",
"main": "app.js",
"scripts": {
"start": "node app.js",
"deploy": "gcloud app deploy",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Ragav",
"license": "ISC",
"dependencies": {
"@google-cloud/datastore": "^1.4.1",
"express": "^4.16.3"
}
}
Также вы должны знать, что это устарело :
runtime: nodejs
vm: true
Вы могли бы сделать это вместо:
runtime: nodejs
env: flex
service: my-service-name