How to use @google-cloud/datastore - 10 common examples

To help you get started, we’ve selected a few @google-cloud/datastore examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sebelga / gstore-node / test / integration / schema.js View on Github external
/* eslint-disable no-unused-expressions */

'use strict';

const chai = require('chai');
const Chance = require('chance');
const { Datastore } = require('@google-cloud/datastore');
const { Gstore } = require('../../lib');

const gstore = new Gstore();
const chance = new Chance();
const ds = new Datastore({ projectId: 'gstore-integration-tests' });
gstore.connect(ds);

const { expect } = chai;
const { Schema } = gstore;

describe('Schema (Integration Tests)', () => {
  beforeEach(() => {
    gstore.models = {};
    gstore.modelSchemas = {};
  });

  it('read param set to "false" should not return those properties from entity.plain()', () => {
    const schema = new Schema({
      email: {
        type: String,
        required: true,
github googleapis / nodejs-datastore / samples / tasks.delete.js View on Github external
async function main(taskId) {
  taskId = Number(taskId);
  // [START datastore_delete_entity]
  const {Datastore} = require('@google-cloud/datastore');

  const datastore = new Datastore();

  async function deleteTask() {
    // TODO(developer): uncomment the following line and define a taskId
    // const taskId = 'task123';
    const taskKey = datastore.key(['Task', taskId]);
    console.log(taskKey);
    await datastore.delete(taskKey);
    console.log(`Task ${taskId} deleted successfully.`);
  }
  deleteTask();
  // [END datastore_delete_entity]
}
github googleapis / nodejs-datastore / samples / concepts.js View on Github external
async function runPageQuery(pageCursor) {
      let query = datastore.createQuery('Task').limit(pageSize);

      if (pageCursor) {
        query = query.start(pageCursor);
      }
      const results = await datastore.runQuery(query);
      const entities = results[0];
      const info = results[1];

      if (info.moreResults !== Datastore.NO_MORE_RESULTS) {
        // If there are more results to retrieve, the end cursor is
        // automatically set on `info`. To get this value directly, access
        // the `endCursor` property.
        const results = await runPageQuery(info.endCursor);

        // Concatenate entities
        results[0] = entities.concat(results[0]);
        return results;
      }

      return [entities, info];
    }
    // [END datastore_cursor_paging]
github GoogleCloudPlatform / nodejs-getting-started / 7-gce / app.js View on Github external
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.set('trust proxy', true);

// Add the request logger before anything else so that it can
// accurately log requests.
app.use(logging.requestLogger);

// Configure the session and session storage.
const sessionConfig = {
  resave: false,
  saveUninitialized: false,
  secret: config.get('SECRET'),
  signed: true,
  store: new DatastoreStore({
    dataset: new Datastore(),
    kind: 'express-sessions',
  }),
};

app.use(session(sessionConfig));

// OAuth2
app.use(passport.initialize());
app.use(passport.session());
app.use(require('./lib/oauth2').router);

// Books
app.use('/books', require('./books/crud'));
app.use('/api/books', require('./books/api'));

// Redirect root to /books
github GoogleCloudPlatform / training-data-analyst / courses / developingapps / v1.2 / nodejs / datastore / end / server / gcp / datastore.js View on Github external
// TODO: Load the @google-cloud/datastore module

const {Datastore} = require('@google-cloud/datastore');

// END TODO

// TODO: Create a Datastore client object, ds
// The Datastore(...) factory function accepts an options 
// object which is used to specify which project's  
// Datastore should be used via the projectId property. 
// The projectId is retrieved from the config module. This 
// module retrieves the project ID from the GCLOUD_PROJECT 
// environment variable.

const ds = new Datastore({
 projectId: config.get('GCLOUD_PROJECT')
});


// END TODO

// TODO: Declare a constant named kind
// The Datastore key is the equivalent of a primary key in a 
// relational database.
// There are two main ways of writing a key:
// 1. Specify the kind, and let Datastore generate a unique 
//    numeric id
// 2. Specify the kind and a unique string id
const kind = 'Question';

// END TODO
github GoogleCloudPlatform / nodejs-getting-started / 2-structured-data / books / model-datastore.js View on Github external
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const {Datastore} = require('@google-cloud/datastore');

// [START config]
const ds = new Datastore();
const kind = 'Book';
// [END config]

// Translates from Datastore's entity format to
// the format expected by the application.
//
// Datastore format:
//   {
//     key: [kind, id],
//     data: {
//       property: value
//     }
//   }
//
// Application format:
//   {
github googleapis / nodejs-datastore / samples / tasks.add.js View on Github external
async function main(description) {
  // [START datastore_add_entity]
  const {Datastore} = require('@google-cloud/datastore');
  const datastore = new Datastore();

  async function addTask() {
    // TODO(developer): uncomment the following line, and add a description
    // const description = 'description';
    const taskKey = datastore.key('Task');
    const entity = {
      key: taskKey,
      data: [
        {
          name: 'created',
          value: new Date().toJSON(),
        },
        {
          name: 'description',
          value: description,
          excludeFromIndexes: true,
github googleapis / nodejs-datastore / samples / quickstart.js View on Github external
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// [START datastore_quickstart]
// Imports the Google Cloud client library
const {Datastore} = require('@google-cloud/datastore');

// Creates a client
const datastore = new Datastore();

async function quickstart() {
  // 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',
github GoogleCloudPlatform / nodejs-getting-started / 4-auth / app.js View on Github external
const app = express();

app.disable('etag');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.set('trust proxy', true);

// [START session]
// Configure the session and session storage.
const sessionConfig = {
  resave: false,
  saveUninitialized: false,
  secret: config.get('SECRET'),
  signed: true,
  store: new DatastoreStore({
    dataset: new Datastore(),
    kind: 'express-sessions',
  }),
};

app.use(session(sessionConfig));
// [END session]

// OAuth2
app.use(passport.initialize());
app.use(passport.session());
app.use(require('./lib/oauth2').router);

// Books
app.use('/books', require('./books/crud'));
app.use('/api/books', require('./books/api'));
github sebelga / gstore-node / __tests__ / integration / index.ts View on Github external
import Chance from 'chance';
import { Datastore } from '@google-cloud/datastore';

import { Gstore, Entity, EntityKey } from '../../src';

type GenericObject = { [key: string]: any };

const gstore = new Gstore();
const ds = new Datastore({ projectId: 'gstore-integration-tests' });
gstore.connect(ds);

const { Schema } = gstore;

interface User {
  name: string;
  modifiedOn?: Date;
}

const userSchema = new Schema({ name: { type: String }, modifiedOn: { type: Date } });
const chance = new Chance();

let generatedIds: string[] = [];
const allKeys: EntityKey[] = [];

const UserModel = gstore.model('GstoreTests-User', userSchema);