Google Cloud Platform support package (gcloud)

Overview

Google Cloud Platform support package (gcloud)

The gcloud package provides a high level "idomatic Dart" interface to some of the most widely used Google Cloud Platform services. Currently the following services are supported:

  • Cloud Datastore
  • Cloud Storage
  • Cloud Pub/Sub

The APIs in this package are all based on the generic generated APIs in the googleapis and googleapis_beta packages.

This means that the authentication model for using the APIs in this package uses the googleapis_auth package.

Note that this package is only intended for being used with the standalone VM in a server or command line application. Don't expect this package to work on the browser.

The code snippets below demonstrating the use of this package all assume that the following imports are present:

import 'package:googleapis_auth/auth_io.dart' as auth;
import 'package:http/http.dart' as http;
import 'package:gcloud/db.dart';
import 'package:gcloud/storage.dart';
import 'package:gcloud/pubsub.dart';
import 'package:gcloud/service_scope.dart' as ss;
import 'package:gcloud/src/datastore_impl.dart';

Getting access to the APIs

The first step in using the APIs is to get an authenticated HTTP client and with that create API class instances for accessing the different APIs. The code below assumes that you have a Google Cloud Project called my-project with credentials for a service account from that project stored in the file my-project.json.

// Read the service account credentials from the file.
var jsonCredentials = new File('my-project.json').readAsStringSync();
var credentials = new auth.ServiceAccountCredentials.fromJson(jsonCredentials);

// Get an HTTP authenticated client using the service account credentials.
var scopes = []
    ..addAll(dastore_impl.DatastoreImpl.SCOPES);
    ..addAll(Storage.SCOPES)
    ..addAll(PubSub.SCOPES)
var client = await auth.clientViaServiceAccount(creds, scopes);

// Instantiate objects to access Cloud Datastore, Cloud Storage
// and Cloud Pub/Sub APIs.
var db = new DatastoreDB(
    new dastore_impl.DatastoreImpl(client, 's~my-project'));
var storage = new Storage(client, 'my-project');
var pubsub = new PubSub(client, 'my-project');

All the APIs in this package supports the use of 'service scopes'. Service scopes are described in details below.

ss.fork(() {
  // register the services in the new service scope.
  registerDbService(db);
  registerStorageService(storage);
  registerPubSubService(pubsub);
  
  // Run application using these services.
});

The services registered with the service scope can now be reached from within all the code running in the same service scope using the below getters.

dbService.
storageService.
pubsubService.

This way it is not necessary to pass the service objects around in your code.

Use with App Engine

The gcloud package is also integrated in the Dart appengine package. This means the gcloud services are available both via the appengine context and service scopes. The authentication required to access the Google Cloud Platform services is handled automatically.

This means that getting to the App Engine Datastore can be through either the App Engine context

var db = context.services.db;

or just using the service scope registration.

var db = dbService;

Cloud Datastore

Google Cloud Datastore provide a NoSQL, schemaless database for storing non-relational data. See the product page https://cloud.google.com/datastore/ for more information.

The Cloud Datastore API provides a mapping of Dart objects to entities stored in the Datastore. The following example shows how to annotate a class to make it possible to store instances of it in the Datastore.

@db.Kind()
class Person extends db.Model {
  @db.StringProperty()
  String name;

  @db.IntProperty()
  int age;
}

The Kind annotation tell that instances of this class can be stored. The class must also inherit from Model. Now to store an object into the Datastore create an instance and use the commit function.

var person = new Person()
    ..name = ''
    ..age = 42;
await db.commit(inserts: [person]);

The function query is used to build a Query object which can be run to perform the query.

var persons = (await db.query(Person).run()).toList();

NOTE: This package include a lower level API provided through the class Datastore on top of which the DatastoreDB API is build. The main reason for this additional API level is to bridge the gap between the different APIs exposed inside App Engine and through the public REST API. We reserve the rights to modify and maybe even remove this additional layer at any time.

Cloud Storage

Google Cloud Storage provide a highly available object store (aka BLOB store). See the product page https://cloud.google.com/storage/ for more information.

In Cloud Storage the objects (BLOBs) are organized in buckets. Each bucket has a name in a global namespace. The following code creates a new bucket named my-bucket and writes the content of the file my-file.txt to the object named my-object.

var bucket = await storage.createBucket('my-bucket');
new File('my-file.txt').openRead().pipe(bucket.write('my-object'));

The following code will read back the object.

bucket.read('my-object').pipe(new File('my-file-copy.txt').openWrite());

Cloud Pub/Sub

Google Cloud Pub/Sub provides many-to-many, asynchronous messaging. See the product page https://cloud.google.com/pubsub/ for more information.

Cloud Pub/Sub uses two concepts for messaging. Topics are used if you want to send messages and subscriptions are used to subscribe to topics and receive the messages. This decouples the producer of a message from the consumer of a message.

The following code creates a topic and sends a simple test message:

var topic = await pubsub.createTopic('my'topic');
await topic.publishString('Hello, world!')

With the following code a subscription is created on the topic and a message is pulled using the subscription. A received message must be acknowledged when the consumer has processed it.

var subscription =
    await pubsub.createSubscription('my-subscription', 'my-topic);
var pullEvent = await subscription.pull();
print(pullEvent.message.asString);
await pullEvent.acknowledge()

It is also possible to receive messages using push events instead of pulling from the subscription. To do this the subscription should be configured as a push subscription with an HTTP endpoint.

await pubsub.createSubscription(
    'my-subscription',
    'my-topic',
    endpoint: Uri.parse('https://server.example.com/push'));

With this subscription all messages will be send to the URL provided in the endpoint argument. The server needs to acknowledge the reception of the message with a 200 OK reply.

Running tests

If you want to run the end-to-end tests, a Google Cloud project is required. When running these tests the following environment variables need to be set:

GCLOUD_E2E_TEST_PROJECT
GCLOUD_E2E_TEST_KEY

The vaule of the environment variable GCLOUD_E2E_TEST_PROJECT is the name of the Google Cloud project to use. The value of the environment variable GCLOUD_E2E_TEST_KEY is a Google Cloud Storage path (starting with gs://) to a JSON key file for a service account providing access to the Cloud Project.

You might also like...

A Flutter application that demonstrate simple CRUD operations with Firebase cloud database.

A Flutter application that demonstrate simple CRUD operations with Firebase cloud database.

Cricket Team A Flutter application that demonstrate simple CRUD operations with Firebase cloud database. Preview Home Empty Swipe Add Player Update Pl

Jun 19, 2021

Cloud storage status

Cloud storage status

cloud_storage_status Get me a coffee: Bitcoin Address: 1DiFn7B9APaQJKfYAKqesnGM2eVM1MW6U Ethereum Address: 0xAdc43dadbE2b64DC9ba1c8766764F7cD4a2Fa915

Jul 23, 2021

A cached Flutter ImageProvider for Firebase Cloud Storage image objects

🔥 Firebase Image Provider A cached Flutter ImageProvider for Firebase Cloud Sto

Nov 2, 2022

Flutter push notifications with Firebase Cloud Messaging.

Flutter push notifications with Firebase Cloud Messaging.

Notify A Flutter sample app demonstrating how to send push notifications using Firebase Cloud Messaging (FCM). Screenshots Notification while the app

Dec 24, 2021

Aprendendo a usar notificações Push com o Firebase Cloud Messaging

Notificações Push com Firebase Esse projeto foi desenvolvido com base no curso "Flutter: Push notifications com Firebase Cloud Messaging", da Alura. P

Dec 28, 2021

Build an example app for receiving notification from Firebase Cloud Messaging (FCM)

notify Build an app demo for receiving notifications from Firebase Cloud Messaging. Check more information: https://firebase.google.com/docs/cloud-mes

Dec 9, 2022

Notey - A noteApp build using flutter with firebase cloud firestore

Notey - A noteApp build using flutter with firebase cloud firestore

notey A project to create and store notes for later purposes. Notey is built usi

Aug 14, 2022

Flutter cloud functions - A sample project demonstrating how to run backend tasks in Flutter

Flutter cloud functions - A sample project demonstrating how to run backend tasks in Flutter

Flutter Cloud Functions A sample project demonstrating how to run backend tasks

Feb 15, 2022

Nimbostratus is a reactive data-fetching and client-side cache management library built on top of Cloud Firestore.

Nimbostratus 🌩 Nimbostratus is a reactive data-fetching and client-side cache management library built on top of Cloud Firestore. The Cloud Firestore

Dec 15, 2022
Owner
Behruz Hurramov
Behruz Hurramov
Behruz Hurramov
A font loader to download, cache and load web fonts in flutter with support for Firebase Cloud Storage.

Dynamic Cached Fonts A simple, easy to use yet customizable font loader to use web fonts. Demo: https://sidrao2006.github.io/dynamic_cached_fonts ?? I

Aneesh Rao 18 Dec 21, 2022
Cross-Platform Google Drive client with encryption support.

arthurmorgan A Cross-Platform Google Drive client with encryption support. Features implemented Google OAuth2 Upload Files Download Single Files Uploa

Washiul Alam Sohan 45 Aug 14, 2023
Dart, Flutter, Google Cloud, and ranked voting!

Try it out Hosted at https://knarlyvote.com tl;dr A (work-in-progress) demonstration of: (1) a full-stack Flutter application utilizing Firebase and G

Kevin Moore 29 Oct 6, 2022
Dota 2 App using Firebase and Google Cloud

Dota 2 App using Firebase and Google Cloud This is a pet project that born with the idea of having a nice subject to go through some Live Coding sessi

Alvaro Viebrantz 39 Dec 15, 2022
A note-taking app powered by Google services such as Google Sign In, Google Drive, and Firebase ML Vision.

Smart Notes A note-taking app powered by Google services such as Google Sign In, Google Drive, and Firebase ML Vision. This is an official entry to Fl

Cross Solutions 88 Oct 26, 2022
💖A free IoT (Internet of Things) platform and private cloud

??A free IoT (Internet of Things) platform and private cloud

Open IoT Hub(云易连) 422 Nov 30, 2022
Flutter plugin, support android/ios.Support crop, flip, rotate, color martix, mix image, add text. merge multi images.

image_editor The version of readme pub and github may be inconsistent, please refer to github. Use native(objc,kotlin) code to handle image data, it i

FlutterCandies 317 Jan 3, 2023
Flutter Download Manager is a Cross-Platform file downloader with Parallel and Batch Download support

Flutter Download Manager is a Cross-Platform file downloader with Parallel and Batch Download support. Manage download tasks by url and be notified of status and their progress. Pause, Cancel, Queue and Resume Downloads.

Nabil Mosharraf 11 Dec 17, 2022
Project demonstrates building a simple chat application using Flutter framework and Firebase cloud

Flutter Chat on Firebase Project demonstrates building a simple chat application using Flutter framework and Firebase cloud. App does not poll for new

Sukitha Udugamasooriya 8 Feb 2, 2022
The prime objective of this app is to store the real time information of the user using firebase cloud firestore and also can delete, remove and update the customer information

crud_firestore A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started i

Muhammad Zakariya 0 Mar 15, 2022