Git Product home page Git Product logo

firebase-functions-interop's People

Contributors

cretezy avatar gazialankus avatar jruillier avatar kevmoo avatar long1eu avatar pulyaevskiy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-functions-interop's Issues

Library 'package:node_interop/http.dart' doesn't export a 'HttpRequest' declaration.

Warning during Dart2JS compilation

bin/packages/firebase_functions_interop/firebase_functions_interop.dart:42:46:
Library 'package:node_interop/http.dart' doesn't export a 'HttpRequest' declaration.
Try removing 'HttpRequest' from the 'show' clause.
export 'package:node_interop/http.dart' show HttpRequest;
                                             ^^^^^^^^^^^

which may lead to error in the execution of the deployed function:

RuntimeError: Cannot resolve 'HttpRequest'.
    at d (/user_code/index.js:1223:3)
    at is (/user_code/index.js:1230:24)
    at ec.dart.ec.$2 (/user_code/index.js:3860:21)
    at cF (/user_code/index.js:1197:112)
    at dart.hy (/user_code/index.js:3716:27)
    at /user_code/index.js:3712:42
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:26:47)
    at /var/tmp/worker/worker.js:671:7
    at /var/tmp/worker/worker.js:655:9
    at _combinedTickCallback (internal/process/next_tick.js:73:7)

my pubspec.yaml:

dependencies:
  firebase_functions_interop: "^0.1.0-beta.2"
  node_interop: ^0.1.0-beta.6

my index.dart:

import 'dart:io';

import 'package:firebase_functions_interop/firebase_functions_interop.dart';

void main() {
  firebaseFunctions['test'] = firebaseFunctions.https.onRequest(test);
}

test(HttpRequest request) {
  request.response.writeln('Hello world');
  request.response.close();
}

Consolidate test functions

Too often Travis builds result in:

You have exceeded your deployment quota, please deploy your functions in batches by using the --only flag, and wait a few minutes before deploying again. Go to https://firebase.google.com/docs/cli/#partial_deploys to learn more.

Should be able to reduce number of functions to one per type (https, database, pubsub, etc).

How do I use generated source maps?

Our functions are working well with this library, but printed stack traces are not human readable. How do we get the source maps to be used so that we can get references to Dart code issues at runtime?

debug dart code in firebase cloud functions emulator

I was about to port my firebase functions from TypeScript to Dart but one of concerns I have now is debugging

I run this command tsc -w | firebase emulators:start --only functions --inspect-functions
and can set break points in VSCode

But how it will work with dart?

document.onUpdate TypeError: Instance of 'UnknownJavaScriptObject': type 'UnknownJavaScriptObject' is not a subtype of type 'Change0<DocumentSnapshot0>'

Running the following code when on document update generates an error

import 'dart:async';
import 'package:firebase_functions_interop/firebase_functions_interop.dart';


void main() {
  functions['updateDocument'] = FirebaseFunctions.firestore.document('{collection}/{document}').onUpdate(onUpdate);
}

FutureOr<void> onUpdate(Change<DocumentSnapshot> change, EventContext context) {
  DocumentSnapshot snapshot = change.after;
  DocumentData updatedDocument = snapshot.data;
  DocumentData previousDocument = change.before.data;
  String updatedAtKey = "updatedAt";

  print('Got Snapshots');

  // If 'updatedAt' is different, that means we have already updated it
  DateTime updatedDocumentTimestamp = updatedDocument.getDateTime(updatedAtKey);
  DateTime previousDocumentTimestamp = previousDocument.getDateTime(updatedAtKey);

  print('Got Timestamps');

  if ((updatedDocumentTimestamp != null) && (previousDocumentTimestamp != null)) {
    if (updatedDocumentTimestamp != previousDocumentTimestamp) {
      print('Timestamps Different Returning');
      return null;
    }
  }

  UpdateData newData = new UpdateData();
  DateTime now = new DateTime.now();
  newData.setDateTime(updatedAtKey, now);

  print('Set update key');

  return snapshot.reference.updateData(newData);
}

I get the following error.

TypeError: Instance of 'UnknownJavaScriptObject': type 'UnknownJavaScriptObject' is not a subtype of type 'Change0<DocumentSnapshot0>'
    at wrapException (/user_code/build/node/index.dart.js:2674:17)
    at assertSubtype (/user_code/build/node/index.dart.js:3428:15)
    at DocumentBuilder_onUpdate_wrapper.dart.DocumentBuilder_onUpdate_wrapper.call$2 (/user_code/build/node/index.dart.js:8971:50)
    at Primitives_applyFunctionWithPositionalArguments (/user_code/build/node/index.dart.js:2622:28)
    at dart._callDartFunctionFast (/user_code/build/node/index.dart.js:8359:14)
    at /user_code/build/node/index.dart.js:8348:18
    at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
    at next (native)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
    at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)

Could be related to #23

My versions are:

dart --version
Dart VM version: 2.0.0-dev.59.0 (Tue May 29 22:11:36 2018 +0200) on "macos_x64"
node --version
v9.5.0
firebase --version
3.18.5

And my pubspec.yaml is:

name: surf_spotter_functions
description: My project functions
version: 0.0.1

environment:
  sdk: '>=2.0.0-dev <2.0.0'

dependencies:
  # Firebase Functions bindings
  firebase_functions_interop: ^1.0.0-dev

dev_dependencies:
  # Needed to compile Dart to valid Node.js module.
  build_runner: ^0.7.9
  build_node_compilers: ^0.1.0

type 'PlainJavaScriptObject' is not a subtype of type 'Change0<DataSnapshot0>'

Cron-executed job produced following error in makeUppercase function

Possibly caused by Dart 2.0.0-dev.52.0 as everything was working fine in dev.51.0.

TypeError: Instance of 'PlainJavaScriptObject': type 'PlainJavaScriptObject' is not a subtype of type 'Change0<DataSnapshot0>'
at wrapException (/user_code/build/node/index.dart.js:3189)
at assertSubtype (/user_code/build/node/index.dart.js:3944)
at RefBuilder_onWrite_wrapper.dart.RefBuilder_onWrite_wrapper.call$2 (index.dart.js:13764)
at Primitives_applyFunctionWithPositionalArguments (/user_code/build/node/index.dart.js:3129)
at dart._callDartFunctionFast (index.dart.js:12981)
at (/user_code/build/node/index.dart.js:12970)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112)
at next (native)
at (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:28)
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24)

Feature to export group of functions

Could we add feature to support adding function into a newObject and then to functions exports.

Let's say if I want to deploy two function functionA and functionB in group alphabet this way:

firebase deploy --only functions:alphabet

at the moment, I would set it up like this

/// index.dart
void main(){
  /// some functionA functionB
  var o = newObject();
  setProperty(
      o,
      'functionA',
      functions.database
          .ref('entries/{user_id}/functionATrigger')
          .onWrite(functionA));
  setProperty(
      o,
      'functionB',
      functions.database
          .ref('entries/{user_id}/functionBTrigger')
          .onWrite(functionB));
  functions['alphabet'] = o;
}

build_runner can't find file

I exactly followed all your installing steps and got this error (verbose for more info):

E:\Development\Projects\XXX\XXX\myproject\functions>pub run build_runner build -v --output=build
[INFO] Generating build script completed, took 581ms
[INFO] BuildDefinition:Initializing inputs
[INFO] BuildDefinition:Reading cached asset graph...
[INFO] BuildDefinition:Reading cached asset graph completed, took 318ms

[INFO] BuildDefinition:Checking for updates since last build...
[INFO] BuildDefinition:Checking for updates since last build completed, took 679ms

[INFO] Build:Running build...
[INFO] Build:Running build completed, took 240ms

[INFO] Build:Caching finalized dependency graph...
[INFO] Build:Caching finalized dependency graph completed, took 172ms

[SEVERE] build_node_compilers|entrypoint on node/index.dart (cached):

ProcessException: Das System kann die angegebene Datei nicht finden.

  Command: E:\Development\flutter\bin\cache\dart-sdk\bin\dart2js.bat --batch
package:build_modules/src/workers.dart 268:22                           _Dart2JsWorker._worker.<fn>
package:build_modules/src/workers.dart 279:6                            _Dart2JsWorker._worker
package:build_modules/src/workers.dart 298:26                           _Dart2JsWorker.doJob
package:build_modules/src/workers.dart 217:14                           Dart2JsBatchWorkerPool._startWorkQueue.<fn>
package:build_modules/src/workers.dart 221:6                            Dart2JsBatchWorkerPool._startWorkQueue
package:build_modules/src/workers.dart 189:26                           Dart2JsBatchWorkerPool.compile
package:build_node_compilers/src/dart2js_bootstrap.dart 48:30           bootstrapDart2Js
package:build_node_compilers/src/node_entrypoint_builder.dart 103:13    NodeEntrypointBuilder.build
package:build                                                           runBuilder
package:build_runner_core/src/generate/build_impl.dart 455:19           _SingleBuild._runForInput.<fn>.<fn>.<fn>
package:build_runner_core/src/generate/performance_tracker.dart 303:15  _NoOpBuilderActionTracker.trackStage
package:build_runner_core/src/generate/build_impl.dart 453:23           _SingleBuild._runForInput.<fn>.<fn>
package:timing/src/timing.dart 222:44                                   NoOpTimeTracker.track
package:build_runner_core/src/generate/build_impl.dart 412:22           _SingleBuild._runForInput.<fn>
dart:async                                                              new Future.sync
package:pool/pool.dart 126:18                                           Pool.withResource.<fn>

[SEVERE] Build:
Failed after 481ms

"Das System kann die angegebene Datei nicht finden." means "The system can not find the stated/given file." in german.

My data structure:
cloud-functions

I'm using Dart Dart VM version: 2.1.0-dev.9.4.flutter-f9ebf21297 (Thu Nov 8 23:00:07 2018 +0100) on "windows_x64" from Flutter.

Content of index.dart:

import 'package:firebase_functions_interop/firebase_functions_interop.dart';

void main() {
  functions['helloWorld'] = functions.https.onRequest(helloWorld);
}

void helloWorld(ExpressHttpRequest request) {
  request.response.writeln('Hello world');
  request.response.close();
}

Content of build.yaml:

targets:
  $default:
    sources:
      - "node/**"
      - "lib/**"
    builders:
      build_node_compilers|entrypoint:
        generate_for:
        - node/**
        options:
          compiler: dart2js
          # List any dart2js specific args here, or omit it.
          dart2js_args:
          - --minify

Content of pubspec.yaml:

name: myproject_functions
description: My project functions
version: 0.0.1

environment:
  sdk: '>=2.0.0-dev <3.0.0'

dependencies:
  # Firebase Functions bindings
  firebase_functions_interop: ^1.0.0

dev_dependencies:
  # Needed to compile Dart to valid Node.js module.
  build_runner: ^1.0.0
  build_node_compilers: ^0.2.0

Can someone resolve this or should I post this at the Repo of build_runner?

Large package when deploying

Firebase creates a 38 MB package when I try to deploy my functions. Usually, my functions have less than 1 mb.

a

Curiously, node_modules has exactly 38 MB, however it is supposed to be automatically ignored (https://stackoverflow.com/a/51182549/6696558).

Is this normal when using this package? Is there any configuration I can do to exclude unwanted parts?

Corrupted `packages` file generated at build

When I run pub run build_runner build --output=build as admin (#56), the corrupted file functions/build/node/packages is generated.

If I run firebase deploy --debug --only functions, I get the following error:

[2019-07-11T18:19:46.508Z] <<< HTTP RESPONSE 200 content-type=application/json; charset=UTF-8, vary=X-Origin, Referer, Origin,Accept-Encoding, date=Thu, 11 Jul 2019 18:19:46 GMT, server=ESF, cache-contro
l=private, x-xss-protection=0, x-frame-options=SAMEORIGIN, x-content-type-options=nosniff, alt-svc=quic=":443"; ma=2592000; v="46,43,39", accept-ranges=none, transfer-encoding=chunked
[2019-07-11T18:19:46.934Z] Error: EPERM: operation not permitted, stat 'C:\Users\hugoc\IdeaProjects\Flutter\buster\functions\build\node\packages'

Error: Could not read source directory. Remove links and shortcuts and try again.

After deleting packages, I'm able to deploy.

I'm using the exact pubspec.yaml, node/index.dart and build.yaml, as shown in the readme.

Unable to send/receive binary data (e.g. Buffer, Uint8List) in HTTPS function

This works with node_interop and Google Cloud Function (binary data is returned in the response):

Uint8List responseBytes = ...;
res
  ..statusCode = 200 // OK
  ..write(Buffer.from(responseBytes))
  ..end();

But with firebase-functions-interop it returns the toString representation of a List<int> of the binary data:

Uint8List responseBytes = ...;
request.response
  ..statusCode = 200 // OK
  ..write(Buffer.from(responseBytes))
  ..close();

Produces the output:

[24, 0, 0, 0, 65, 67, 77, 46, 16,...]

Timeout issue

Hi Anatoly,

I have now productionalized the code that is using your library and it all works as expected on small test data samples but once I start putting trough 'proper' data volumes I get a timeout exception on the Flutter side (using the cloud_functions library). The exception is a bit suspicious though as it does not seem to be 'properly formed'. I have been experimenting with data volumes and code changes but cannot get to the bottom of this. I have seen your name in the cloud_functions commit log as well so I though you might have some ideas that will push me in the right direction since you know both libraries.

Bit of context to start with. Part of the Flutter code that uses the Firebase function is doing some data loading and transformation (running on an Android phone I have not tested it on iPhone). The transformation part is quite time consuming and it take some considerable time on older mobiles so I have moved it to the cloud function (server).

The Flutter side (client) extracts first some pieces of data that is required for transformation. This is a list of maps each map containing three items - String identifier, String description and an integer amount. In my tests the number of entries was about 700 to start with but I was getting errors even with as little as 180 entries. The time print outs below are for 700 entries.

This list is pushed to the server by the CloudFunctions.instance.call(...) method and picked up on the other end:

functions['applyRules'] = FirebaseFunctions.https.onCall((dynamic data, CallableContext ctx) => rules(monitoring, data));

Which calls this method:

Map<String, dynamic> rules( Monitoring monitoring, Map<String, dynamic> request) { ... }

I have also tried returning a Future from this method but that did not make any difference.

The data is correctly transported to the server, the server correctly transforms the data but as the server is running the transformation the client gets an exception from the StandardMethodCodec class which I have enhanced a bit to get more info:

  @override
  dynamic decodeEnvelope(ByteData envelope) {
    // First byte is zero in success case, and non-zero otherwise.
    if (envelope.lengthInBytes == 0)
      throw const FormatException('Expected envelope, got nothing');
    final ReadBuffer buffer = ReadBuffer(envelope);

    var xx = buffer.getUint8();
    if (xx == 0)
      return messageCodec.readValue(buffer);


    final dynamic errorCode = messageCodec.readValue(buffer);
    final dynamic errorMessage = messageCodec.readValue(buffer);
    final dynamic errorDetails = messageCodec.readValue(buffer);

    print('************************************************************');
    print('      buffer.getUint8() [${xx}]');
    print('    errorCode is String [${errorCode is String}]');
    print('              errorCode [$errorCode]');
    print('           errorMessage [$errorMessage]');
    print(' errorMessage is String [${errorMessage is String}]');
    print('           errorDetails [$errorDetails]');
    print('    buffer.hasRemaining [${buffer.hasRemaining}]');
    print('************************************************************');

    if (errorCode is String && (errorMessage == null || errorMessage is String) && !buffer.hasRemaining)
      throw PlatformException(code: errorCode, message: errorMessage, details: errorDetails);
    else
      throw const FormatException('Invalid envelope');
  }

This is the client side printout and the exception:

[2018-12-02 11:44:42.857813] Before CloudFunctions
...

************************************************************
       buffer.getUint8() [1]
     errorCode is String [false]
               errorCode [null]
            errorMessage [timeout]
  errorMessage is String [true]
            errorDetails [null]
     buffer.hasRemaining [false]
************************************************************

[2018-12-02 11:44:53.430352] exception

FormatException: Invalid envelope

What is a bit suspicious is that the errorCode is null (although this might be a bug in the underlying Android code).

I also logged the server start and end time and the server finished after the client threw the exception.

2018-12-02 11:44:44.292727489Z	Function execution started

2018-12-02 11:45:18.311019222Z	Function execution took 34020 ms, finished with status code: 200

What is interesting that with the 700 items data set the exception is throw after ~ 11 seconds (based on two observations). Maybe this is a genuine timeout and I need to change a time out property somewhere (as far as I can tell there is none in the Flutter code). But then as I said this happens with much smaller data sets as well which take less time to process.

Regards,
Adam

Cloud Functions Plugin/Firebase Functions Interop Issue

I have finally wired it all up using the Cloud Functions Plugin on my Flutter client to call the function but now getting a CloudFunctionsException/Response is missing data field on the client after the call returns.

I/flutter ( 6077): throwing firebase functions exception
I/flutter ( 6077): Firebase exception: Instance of 'CloudFunctionsException'
I/flutter ( 6077): code: INTERNAL
I/flutter ( 6077): message: Response is missing data field.
I/flutter ( 6077): details: null

I have tried this with a simple 'Hello world' function as well (which returns a correct response in the browser) and getting the same issue. Just wondering if I need to construct the response differently for the client plugin be able to consume it.

Regards,
Adam

onCreate is calling native onWrite

in file firebase_functions_interop.dart ln 168

js.CloudFunction onCreate(FutureOr handler(DatabaseEvent event),
[Serializer serializer]) {
dynamic wrapper(js.Event event) {
return _handleEvent(event, handler, serializer);
}

return nativeInstance.onWrite(allowInterop(wrapper));

}

shold be
return nativeInstance.onCreate(allowInterop(wrapper));

same for onDelete and onUpdate

Functions Not Detected/Deployed

Issue: Firebase cmdline utility does not detect any Firebase functions written in Dart.

Steps to Reproduce:

  1. File: functions/pubspec.yaml

dependencies:
  firebase_admin_interop: ^1.2.2
  firebase_functions_interop: ^1.0.0+1

dev_dependencies:
  build_runner: ^1.2.3
  build_node_compilers: ^0.2.1

environment:
  sdk: '>=2.0.0 <3.0.0'
  1. File: functions/package.json
  "name": "test",
  "dependencies": {
    "firebase-admin": "7.1.1",
    "firebase-functions": "2.2.1",
    "@google-cloud/firestore": "1.2.0"
  },
  "main": "build/node/index.dart.js",
  "private": true
}
  1. File: functions/node/index.dart
import 'dart:async';
import 'package:firebase_functions_interop/firebase_functions_interop.dart';

void main() {
  functions['helloWorld'] = functions.https.onRequest(helloWorld);
}

Future<void> helloWorld(ExpressHttpRequest request) async {
  try {
    request.response.writeln('Hello world');
  } finally {
    request.response.close();
  }
}
  1. File: functions/build.yaml
  $default:
    sources:
      - "node/**"
      - "lib/**"
    builders:
      build_node_compilers|entrypoint:
        generate_for:
        - node/**
        options:
          compiler: dart2js
          dart2js_args:
          - --minify
  1. Command (working directory: functions/) pub run build_runner build
  2. Command (working directory: /) firebase deploy --only functions
  3. Expect: Function is deployed. Actual: No functions are detected or deployed.

Versions:
dart --version is 2.2.0
firebase --version is 6.5.0
npm --version is 6.4.1 (to match what Firebase uses)

Using a JavaScript library

How can we call JavaScript code from our Dart code? I can't see how the js code can be included here.

In Web, you need to already have the js code included in the js side and you tell Dart to call that. So, we need access to the js side. However, firebase-functions-interop way is to point node.js to the generated build/node/index.dart.js file.

I guess I could just edit the generated js file at every build, but I'm hoping for a better approach.

Thanks!

SetList option gives me an error when writing a list of maps.

Thanks for this great package! I am having one problem. I am getting an error when using setList to write a list of maps.

When I try and write to firestore and update a document with the setList option it gives me an error.

Unsupported operation: Value of type minified:b1 is not supported by Firestore.

I have a model that has a list of activities (a log of what the property has done)

class Property {
  String id;
  String owner;
  String email;
  List<Invoice> invoices;
  List<LogModel> activity;

  Property(
      {this.id,
      this.owner,
      this.email,
      this.activity});

  factory Property.fromMap(Map data) {
    return Property(
      id: data['id'],
      owner: data['owner'] ?? '',
      email: data['email'] ?? '',
      activity: (data['activity'] as List ?? [])
          .map((v) => LogModel.fromMap(v))
          .toList(),
    );
  }

  Map<String, dynamic> toJson() => {
        "id": id,
        "owner": owner,
        "email": email,
        "activity": List<dynamic>.from(activity.map((x) => x.toJson())),
      };
}

class LogModel {
  String id;
  String user;
  String message;
  int date;

  LogModel({this.id, this.user, this.message, this.date});

  LogModel.fromMap(Map data) {
    id = data['id'];
    user = data['user'] ?? '';
    message = data['message'] ?? '';
    date = data['date'];
  }

  Map<String, dynamic> toJson() => {
        "id": id,
        "user": user,
        "message": message,
        "date": date,
      };
}
 UpdateData propertyData = UpdateData();
  propertyData.setString("email", property.email);
  propertyData.setList("activity", property.activity);

  final ref = app.firestore().document('/properties/${property.id}');

  await ref.updateData(propertyData);

Thanks so much for any advice on how to handle this situation when it is a list of Maps.

Running a HTTP client over TLS 1.2 from a cloud function

I am implementing the OAuth 2.0 'authorization code grant' flavour with an option of using the TLS 1.2 protocol. I am using dart.io for the front channel (with the SecurityContext for the TLS option) and a cloud function for the back channel (callback).

During the token exchange phase the back channel starts a http client to call the authorization server to get the token. So the client needs to run over the TLS when this is required.

I had a look into the package:node_http/node_http.dart but I could not see a way to start a http client with the certificate/key. As far as I know the underlying node.js supports SSL/TLS. Would it be possible to expose this in the interop Dart layer?

Firestore Timestamp Support

Firestore will be disabling the use of native date & time implementations with Timestamp fields in favour of their Timestamp class by (I think) the end of 2019. It is already possible in all official Firestore packages to opt-in to using the Timestamp class, but Timestamp support will soon be required to handle Timestamp fields in all Firestore packages. The JavaScript package itself already includes support for the Timestamp class, so I wouldn't expect it to be too difficult to implement in this package.

Figuring out how to schedule cron functions

I love using this so much more than trying to work in javascript instead of Dart, so thanks. I'm using this to check all the upcoming events and send notifications to the members. I got almost everything done, and it should be working, but the hard part was creating a function[] for a scheduledTask to check the event start times. I got it implemented with this cron package https://pub.dartlang.org/packages/cron and it was really easy to use in my main, I can't figure out how to run it as a cloud function. This was my attempt:

functions['scheduleCheck'] = cron.schedule(new Schedule.parse('*/$minuteInterval * * * *'), () async {
    print('Tick every $minuteInterval minutes');
}

However it wasn't as simple as I thought. Is there a trick I might be missing? I'd be so happy to see this cloud function hold together, perfect companion for them Flutter apps.
If I were doing it in the javaScript method, I would create the cron.yaml with the repeating event as in this example: https://github.com/FirebaseExtended/functions-cron but I don't know how that translates in Dart.
To send out the Firestore Cloud Messaging, I'm using this https://pub.dartlang.org/packages/fcm_push which seems to be compatible so far, but haven't pushed tested yet. I was expecting a FCM method built into this, but was glad to find the solution.
Anyways, thanks for this interop, I'm feeling safe using it..

serve is failing due to firebase-admin not being installed

I've started getting an error message when I try to serve firebase functions:

The Cloud Functions emulator requires the module "firebase-admin" to be installed. This package is in your package.json, but it's not available. You probably need to run "npm install" in your functions directory.

I've tried running npm install, I've also tried

npm install firebase-functions@latest --save
npm install firebase-admin@latest --save-exact

which was suggested on the official docs.

My package.json looks like this:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "build": "pub run build_runner build --output=build",
    "watch": "pub run build_runner watch --output=build",
    "preserve": "npm run build",
    "serve": "firebase serve --only functions",
    "predeploy": "npm run build",
    "deploy": "firebase deploy --only functions",
    "preshell": "npm run build",
    "shell": "firebase experimental:functions:shell",
    "start": "npm run shell",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "@google-cloud/firestore": "0.18.0",
    "firebase-admin": "8.5.0",
    "firebase-functions": "^3.2.0"
  },
  "private": true,
  "main": "build/node/index.dart.js"
}

Versions are as follows:

  • Dart VM version: 2.5.0-dev.2.1 (Thu Aug 15 16:05:39 2019 +0200) on "macos_x64"
  • Node: v8.9.1
  • Firebase: 7.3.1

TransactionResult doesn't allow abort on non dynamic data

await database.ref('queue').transaction<Map<String, dynamic>>(
  (currentData) {
    print(currentData);
    if (currentData.length.isOdd) {
      print('aborting!');
      return TransactionResult.abort;
    }
    print('hand waving done');
    return TransactionResult.success(currentData);
  },
);

I'm running into a compile issue with this code. The transaction.abort line gives an error saying: The return type 'TransactionResult<dynamic>' isn't a 'TransactionResult<Map<String, dynamic>>', as required by the closure's context.

Am I allowed to specify the transaction type?

firebase_interop package

Could we also create firebase_interop package? I am aware there is already the firebase package for Flutter and Web. Though it does not work on node, or planned to focus on node.

One of the reason I would want to have it on node is to write apis for clients that first runs in node before actually get on the browser.

Another reason is that the firebase and firebase-admin libraries share many similarities between then database and firestore. I would suggest to be able to seperate those two from the admin_interop in the future.

This is my use case:

class Context{
  Database realtime;
  Firestore firestore;
}
mixin CartWriter implements Context, NodeBase {
  update(){
    realtime.ref(this.ref).update(this.toJSON);
  }
}

Now if I want to user CartWriter for both server and client, it's a little tricky because it has to distinguish between Database from firebase and one from firebase-admin.
One requirement is that the client API cannot import firebase_admin_interop.dart because it includes the require('firebase-admin'), which shouldn't be packaged together in the build.

What do you think?

OnCreate Error

Hello I'm trying to write a function so that i can change the data when a user was created.
The following doesn't work. What am I doing wrong?

Doesn't it work with my model object of the user since i have some dependencies
in this package

name: foundation
description: A starting point for Dart libraries or applications.
# version: 1.0.0
# homepage: https://www.example.com

environment:
  sdk: '>=2.5.0 <3.0.0'

dependencies:
  quiver: ^2.0.5

  intl: ^0.16.0


dev_dependencies:
  pedantic: ^1.8.0
  test: ^1.6.0

I'm getting all the time in the logs errors like these however there is no useable information inside.

TypeError: u.bx is not a function
    at Object.lJ (/srv/build/node/index.dart.js:1628:63)
    at fq.mv (/srv/build/node/index.dart.js:1756:5)
    at dX.aW (/srv/build/node/index.dart.js:3771:5)
    at dZ.$2 (/srv/build/node/index.dart.js:3775:32)
    at Object.lP (/srv/build/node/index.dart.js:187:112)
    at me (/srv/build/node/index.dart.js:1424:10)
    at /srv/build/node/index.dart.js:1418:42
    at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
    at /worker/worker.js:825:24
    at <anonymous>

Here is the code I tried:

void main() {
  functions['createUser'] =
      functions.firestore.document('/users/{userId}').onCreate(createUser);
}

FutureOr<void> createUser(DocumentSnapshot snap, EventContext context) {
  final user = User.fromJson(snap.data.toMap());
  final newUser = user.copy(idUser: 'hello_word');

  final newDoc = DocumentData.fromMap(newUser.toJson());

  return snap.reference.setData(newDoc);
}

Deployment error

Getting this error during the deployment. Not sure if this is a Firebase issue or the generated code is invalid. When I googled this found somewhat similar problems that were resolved by downgrading the Firebase tools versions.

image

These are two functions that I am deploying. However when I remove the 'applySystemPayeeRules' method and the dependency on the the library where this is implemented all is good. So this makes me think that maybe the generated code is not quite right.

image

Here is the 'index.dart.js' if that helps.
index.dart.js.zip

Fails to compile with node_io 1.0.0

Thanks again for your package. The latest change you made to node_io (1.0.0) seems to break this package.
Tested on sdk 2.3.0-dev.0.0 Ubuntu.

The workaround for me for now is to add the following constraint:

  node_io: 1.0.0-dev.10.0

TypeError: Instance of 'JSArray': type 'JSArray' is not a subtype of type 'List<String>'

When I post the following JSON to a cloud function I get the above error message.

{"array":["element1", "element2"]}

Example code:

void main() {
  functions['test'] = FirebaseFunctions.https.onRequest((ExpressHttpRequest request) async {
    final data = request.body;
    List<String> stringArray = data["array"];
    print(stringArray);
  });
}

This was working in an earlier Dart version. I'm using:
Dart VM version: 2.0.0-dev.67.0 (Tue Jul 3 18:17:07 2018 +0200) on "macos_x64"

I guess this is more of a node_interop problem, since the dartify function is defined there. Firebase-dart uses a very similar dartify function. I'm wondering if they see a similar issue.

Privilege error when building

When I run pub run build_runner build --output=build, I get the following output:

[INFO] Generating build script completed, took 252ms
[WARNING] Throwing away cached asset graph due to Dart SDK update.
[INFO] Cleaning up outputs from previous builds. completed, took 32ms
[INFO] Generating build script completed, took 64ms
[INFO] Creating build script snapshot... completed, took 7.0s
[INFO] Building new asset graph completed, took 722ms
[INFO] Checking for unexpected pre-existing outputs. completed, took 1ms
[INFO] build_node_compilers:entrypoint on node/index.dart:Running dart2js with --minify --packages=.package-331d3db0d4c542b2c2c29095d74263e9 -onode/index.dart.js node/index.dart
[INFO] build_node_compilers:entrypoint on node/index.dart:Dart2Js finished with:

Compiled 7,908,073 characters Dart to 85,934 characters JavaScript in 2.15 seconds
Dart file node\index.dart compiled to JavaScript: node/index.dart.js

[INFO] Running build completed, took 3.0s
[INFO] Caching finalized dependency graph completed, took 85ms
[INFO] Creating merged output dir `build`...

You have hit a bug in build_runner
Please file an issue with reproduction steps at https://github.com/dart-lang/build/issues

FileSystemException: Cannot create link, path = 'build\node\packages' (OS Error: A required privilege is not held by the client.
, errno = 1314)
dart:io                                                                       _Link.createSync
package:build_runner_core/src/environment/create_merged_dir.dart 93:16        _createMergedOutputDir.<fn>
package:build_runner_core/src/logging/logging.dart 25:30                      logTimedAsync
package:build_runner_core/src/environment/create_merged_dir.dart 72:9         _createMergedOutputDir
package:build_runner_core/src/environment/create_merged_dir.dart 44:16        createMergedOutputDirectories
package:build_runner_core/src/environment/io_environment.dart 81:18           IOEnvironment.finalizeBuild
package:build_runner_core/src/environment/overridable_environment.dart 52:49  OverrideableEnvironment.finalizeBuild
package:build_runner_core/src/generate/build_impl.dart 218:33                 _SingleBuild.run
package:build_runner_core/src/generate/build_impl.dart 93:42                  BuildImpl.run
package:build_runner_core/src/generate/build_runner.dart 24:14                BuildRunner.run
package:build_runner/src/generate/build.dart 111:30                           build
package:build_runner/src/entrypoint/build.dart 28:24                          BuildCommand.run
package:args/command_runner.dart 197:27                                       CommandRunner.runCommand
package:args/command_runner.dart 112:25                                       CommandRunner.run.<fn>
dart:async                                                                    new Future.sync
package:args/command_runner.dart 112:14                                       CommandRunner.run
package:build_runner/src/entrypoint/run.dart 23:31                            run
.dart_tool\build\entrypoint\build.dart 78:22                                  main

I'm using the exact pubspec.yaml, node/index.dart and build.yaml as shown in the readme.

The command works when I run it in a terminal with admin permissions.

Dart VM version: 2.4.0

firebase deploy is failing

I am new to Dart and although I love it, I struggle to find my way around it.

I followed the steps on this repo. I get a successful build:

pub run build_runner build
[INFO] Generating build script completed, took 250ms
[INFO] Reading cached asset graph completed, took 186ms
[INFO] Checking for updates since last build completed, took 599ms
[INFO] build_node_compilers|entrypoint on node/index.dart:Running dart2js with --checked --packages=.package-7d9a89460320ecd0b7469657b140821c -onode/index.dart.js node/index.dart
[INFO] build_node_compilers|entrypoint on node/index.dart:Dart2Js finished with:

Compiled 8,921,032 characters Dart to 378,822 characters JavaScript in 3.03 seconds
Dart file (node/index.dart) compiled to JavaScript: node/index.dart.js

[INFO] Running build completed, took 3.4s
[INFO] Caching finalized dependency graph completed, took 90ms
[INFO] Succeeded after 3.5s with 5 outputs

Then when I try to deploy I get the following:

firebase deploy --only functions --debug
[2018-05-11T11:31:43.558Z] ----------------------------------------------------------------------
[2018-05-11T11:31:43.561Z] Command: /usr/local/Cellar/node/9.5.0/bin/node /usr/local/bin/firebase deploy --only functions --debug
[2018-05-11T11:31:43.561Z] CLI Version: 3.18.4
[2018-05-11T11:31:43.561Z] Platform: darwin
[2018-05-11T11:31:43.561Z] Node Version: v9.5.0
[2018-05-11T11:31:43.562Z] Time: Fri May 11 2018 14:31:43 GMT+0300 (EEST)
[2018-05-11T11:31:43.562Z] ----------------------------------------------------------------------

[2018-05-11T11:31:43.576Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"]
[2018-05-11T11:31:43.577Z] > authorizing via signed-in user
[2018-05-11T11:31:43.579Z] >>> HTTP REQUEST GET https://admin.firebase.com/v1/projects/kitespotter2-57429

Fri May 11 2018 14:31:43 GMT+0300 (EEST)
[2018-05-11T11:31:44.565Z] <<< HTTP RESPONSE 200 server=nginx, date=Fri, 11 May 2018 11:31:44 GMT, content-type=application/json; charset=utf-8, content-length=122, connection=close, x-content-type-options=nosniff, strict-transport-security=max-age=31536000; includeSubdomains, cache-control=no-cache, no-store
[2018-05-11T11:31:44.565Z] >>> HTTP REQUEST GET https://admin.firebase.com/v1/database/kitespotter2-57429/tokens

Fri May 11 2018 14:31:44 GMT+0300 (EEST)
[2018-05-11T11:31:45.474Z] <<< HTTP RESPONSE 200 server=nginx, date=Fri, 11 May 2018 11:31:45 GMT, content-type=application/json; charset=utf-8, content-length=268, connection=close, x-content-type-options=nosniff, strict-transport-security=max-age=31536000; includeSubdomains, cache-control=no-cache, no-store

=== Deploying to 'kitespotter2-57429'...

i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint

functions@ lint /Users/zirinisp/Documents/Dart/SurfSpotterDartCloudFunctions/functions
eslint .

/Users/zirinisp/Documents/Dart/SurfSpotterDartCloudFunctions/functions/build/node/index.dart.js
1:106 error Expected '!==' and instead saw '!=' eqeqeq
1:375 error Use '===' to compare with null no-eq-null
1:379 error Expected '===' and instead saw '==' eqeqeq
1:530 error Use '===' to compare with null no-eq-null
1:534 error Expected '!==' and instead saw '!=' eqeqeq
1:551 error Use '===' to compare with null no-eq-null
1:555 error Expected '!==' and instead saw '!=' eqeqeq
1:648 warning Value of 'e' may be overwritten in IE 8 and earlier no-catch-shadow
31:28 error Expected '!==' and instead saw '!=' eqeqeq
31:73 error Expected '===' and instead saw '==' eqeqeq
33:26 error Expected '===' and instead saw '==' eqeqeq
33:58 error Expected '===' and instead saw '==' eqeqeq

then hundreds of similar lines. That end with:

17358:623 error Unexpected comma in middle of array no-sparse-arrays
17358:765 error Unexpected comma in middle of array no-sparse-arrays
17358:850 error Unexpected comma in middle of array no-sparse-arrays
17358:873 error Unexpected comma in middle of array no-sparse-arrays
17358:953 error Unexpected comma in middle of array no-sparse-arrays
17358:1100 error Unexpected comma in middle of array no-sparse-arrays
17358:1128 error Unexpected comma in middle of array no-sparse-arrays
17358:1210 error Unexpected comma in middle of array no-sparse-arrays
17358:1245 error Unexpected comma in middle of array no-sparse-arrays
17358:1279 error Unexpected comma in middle of array no-sparse-arrays
17415:20 error Expected '===' and instead saw '==' eqeqeq
17445:18 error 'i' is already defined no-redeclare
17451:18 error 'i' is already defined no-redeclare
17492:39 error Expected '!==' and instead saw '!=' eqeqeq
17504:6 warning Unexpected function expression prefer-arrow-callback
17507:22 warning Unexpected function expression prefer-arrow-callback

/Users/zirinisp/Documents/Dart/SurfSpotterDartCloudFunctions/functions/build/packages/build_runner/src/server/graph_viz.js
9:27 error Expected '===' and instead saw '==' eqeqeq
9:49 error Expected '===' and instead saw '==' eqeqeq
17:18 error 'i' is already defined no-redeclare
22:25 error Expected '===' and instead saw '==' eqeqeq
68:43 warning Unexpected function expression prefer-arrow-callback
76:37 warning Expected to return a value at the end of function consistent-return
76:37 warning Unexpected function expression prefer-arrow-callback

/Users/zirinisp/Documents/Dart/SurfSpotterDartCloudFunctions/functions/build/packages/node_preamble/preamble.js
9:26 error Expected '!==' and instead saw '!=' eqeqeq
32:13 error Use '===' to compare with null no-eq-null
32:19 error Expected '!==' and instead saw '!=' eqeqeq
33:16 error Use '===' to compare with null no-eq-null
33:22 error Expected '!==' and instead saw '!=' eqeqeq
41:11 error Use '===' to compare with null no-eq-null
41:31 error Expected '===' and instead saw '==' eqeqeq

/Users/zirinisp/Documents/Dart/SurfSpotterDartCloudFunctions/functions/build/packages/node_preamble/preamble.min.js
1:106 error Expected '!==' and instead saw '!=' eqeqeq
1:375 error Use '===' to compare with null no-eq-null
1:379 error Expected '===' and instead saw '==' eqeqeq
1:530 error Use '===' to compare with null no-eq-null
1:534 error Expected '!==' and instead saw '!=' eqeqeq
1:551 error Use '===' to compare with null no-eq-null
1:555 error Expected '!==' and instead saw '!=' eqeqeq
1:648 warning Value of 'e' may be overwritten in IE 8 and earlier no-catch-shadow

โœ– 59879 problems (53427 errors, 6452 warnings)
6381 errors, 3211 warnings potentially fixable with the --fix option.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: eslint .
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/zirinisp/.npm/_logs/2018-05-11T11_36_12_515Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code1

My index.dart file is the following:

// Examples on: https://pub.dartlang.org/packages/firebase_functions_interop/versions/1.0.0-dev.4.0#-example-tab-

import 'dart:async';
import 'package:firebase_functions_interop/firebase_functions_interop.dart';


void main() {
  functions['createDocument'] = FirebaseFunctions.firestore.document('{collection}/{document}').onCreate(onCreate);
  functions['updateDocument'] = FirebaseFunctions.firestore.document('{collection}/{document}').onUpdate(onUpdate);
}

void helloWorld(ExpressHttpRequest request) {
  request.response.writeln('Hello world');
  request.response.close();
}

FutureOr<void> onCreate(DocumentSnapshot snapshot, EventContext context) {
  DocumentData newDocument = snapshot.data;
  String createdAtKey = "createdAt";

  // If there is a createdAt field already, return to avoid loops
  if (newDocument.getDateTime(createdAtKey) != null) return null;

  UpdateData newData = new UpdateData();
  DateTime now = new DateTime.now();
  newData.setDateTime(createdAtKey, now);

  return snapshot.reference.updateData(newData);
}

FutureOr<void> onUpdate(Change<DocumentSnapshot> change, EventContext context) {
  DocumentSnapshot snapshot = change.after;
  DocumentData updatedDocument = snapshot.data;
  DocumentData previousDocument = change.before.data;
  String updatedAtKey = "updatedAt";

  // If 'updatedAt' is different, that means we have already updated it
  if (updatedDocument.getDateTime(updatedAtKey) != previousDocument.getDateTime(updatedAtKey))
    return null;

  UpdateData newData = new UpdateData();
  DateTime now = new DateTime.now();
  newData.setDateTime(updatedAtKey, now);

  return snapshot.reference.updateData(newData);
}

Can you please help me out on how I can deploy.

Build with/without the `minify` flag produces almost the same uploaded code size

I have noticed that running the build with the minify flag does not seem to make much difference when it comes to the size of the actual code that is uploaded to the server.

Without the flag I get:

Compiled 9,615,889 characters Dart to 1,133,281 characters JavaScript in 10.4 seconds
...
functions: packaged functions (67.32 MB) for uploading

and with the flag:

Compiled 9,615,392 characters Dart to 429,438 characters JavaScript in 10.9 seconds
...
functions: packaged functions (67.12 MB) for uploading

Since the minified code is less then half of the non-minified I would expect much bigger reduction in the code that is uploaded as well.

Can't import firebase_functions_interop.dart

I created a project with reference to the README, but I can't import package:firebase_functions_interop/firebase_functions_interop.dart.

index.dart:
screenshot

pubspec.yaml:

name: firebase_functions_test
description: test.
version: 0.0.1

environment:
  sdk: ">=2.0.0-dev <3.0.0"

dependencies:
  firebase_functions_interop: ^1.0.0-dev

dev_dependencies:
  build_runner: ^1.0.0
  build_node_compilers: ^0.2.0

Having difficulties building

When I try to build I get the error below. I doesn't list any imports for me check. Is there a way I can figure out what is library or source is the cause of the problems?

> functions@ build /Users/jimmyff/Development/datingnode/functions
> pub run build_runner build --output=build

[INFO] Generating build script completed, took 319ms
[INFO] Reading cached asset graph completed, took 253ms
[INFO] Checking for updates since last build completed, took 785ms
[INFO] Running build completed, took 184ms
[INFO] Caching finalized dependency graph completed, took 149ms
[SEVERE] build_node_compilers|entrypoint on node/index.dart (cached):

Unable to find modules for some sources, this is usually the result of either a
bad import, a missing dependency in a package (or possibly a dev_dependency
needs to move to a real dependency), or a build failure (if importing a
generated file).

Please check the following imports:


[SEVERE] Failed after 349ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ build: `pub run build_runner build --output=build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the functions@ build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/jimmyff/.npm/_logs/2019-03-19T12_29_35_126Z-debug.log
The terminal process terminated with exit code: 1

Terminal will be reused by tasks, press any key to close it.

This is the contents of /Users/jimmyff/.npm/_logs/2019-03-19T12_29_35_126Z-debug.log

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'run', 'build' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle functions@~prebuild: functions@
6 info lifecycle functions@~build: functions@
7 verbose lifecycle functions@~build: unsafe-perm in lifecycle true
8 verbose lifecycle functions@~build: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/jimmyff/Development/datingnode/functions/node_modules/.bin://chromium_depot_tools:/Users/jimmyff/flutter-sdk/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/VMware Fusion.app/Contents/Public:/usr/local/git/bin:~/.pub-cache/bin
9 verbose lifecycle functions@~build: CWD: /Users/jimmyff/Development/datingnode/functions
10 silly lifecycle functions@~build: Args: [ '-c', 'pub run build_runner build --output=build' ]
11 silly lifecycle functions@~build: Returned: code: 1  signal: null
12 info lifecycle functions@~build: Failed to exec build script
13 verbose stack Error: functions@ build: `pub run build_runner build --output=build`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at EventEmitter.emit (events.js:214:7)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at ChildProcess.emit (events.js:214:7)
13 verbose stack     at maybeClose (internal/child_process.js:925:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
14 verbose pkgid functions@
15 verbose cwd /Users/jimmyff/Development/datingnode/functions
16 verbose Darwin 18.0.0
17 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "build"
18 verbose node v8.9.1
19 verbose npm  v6.4.1
20 error code ELIFECYCLE
21 error errno 1
22 error functions@ build: `pub run build_runner build --output=build`
22 error Exit status 1
23 error Failed at the functions@ build script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

Integrating FCM or PubSub Push

I'm facing problems using the Dart fcm_push or the pubsub push in gcloud. I installed the gcloud, googleapis and googleapis_auth dependencies, and set up the ServiceAccountCredentials to get the AuthClient, and everything seems to be done right, however I get this uncaught exception in the log:
ReferenceError: XMLHttpRequest is not defined
at /user_code/build/node/main.dart.js:9351:7

I just can't get past that, no matter what I tried. Is there a trick I'm missing, or a better way to push notifications to subscribers or user token ids using this interop? Here is my pubsub.yaml:

dependencies:
  firebase_functions_interop: ^1.0.0
  fcm_push: ^1.3.1
  gcloud: ^0.6.0+4
  googleapis: ^0.53.0
  cron: ^0.2.2

dev_dependencies:
  build_runner: ^1.0.0
  build_node_compilers: ^0.2.0
  googleapis_auth: '>=0.2.3 <0.3.0'

and my relevant imports:

import 'package:fcm_push/fcm_push.dart' as fcm;
import 'package:googleapis_auth/auth_io.dart' as auth;
import 'package:http/http.dart' as http;
import 'package:gcloud/pubsub.dart' as pubsub; 

and my code to init the client:

auth.AuthClient client;
pubsub.PubSub pubSub;
fcm.FCM cloudMessaging;

  var credentials = auth.ServiceAccountCredentials.fromJson(r'''
{
  "type": "service_account",
  "project_id": "....",
  "private_key_id": "....",
//Taken from key credentials json download
}
''');
  var scopes = pubsub.PubSub.SCOPES;
  print("Init 1 - auth client Metadata");
  client = await auth.clientViaServiceAccount(credentials, scopes);
  //client = await auth.clientViaMetadataServer();
  print("Init 2 - Getting pubSub");
  pubSub = new pubsub.PubSub(client, "functions");

Everything builds/deploys correctly, except in the log with the client auth, or try to do a cloudMessaging.send() I get that pesky XMLHttpRequest is not defined error that I can't find anything about fixing. Has anyone else been able to send push notifications from their Firebase Functions trigger? Seems like it would be a common use case, any help would be appreciated, thanks..

[Question \ Feature request] Make write to Firestore (Firebase-admin functions)

Is there a way to read\write to Firestore database inside of HTTPS function?

From what I see in Cloud Functions specs - I need to run this in Node.JS:

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

I'm not familiar with JS though so all my hope was on firebase-functions-interop plugin.

Select/update Firestore document

Is there a way to select/update a specific Firestore document (FirebaseFunctions.firestore.document returns event handlers only)?

According to this stack overflow question in JavaScript it is done something like this:

admin
    .firestore()
    .collection('ruleSets')
    .doc(1234)
    .get()
    .then(doc => {
         console.log('Got rule: ' + doc.data().name);
     });

admin.firestore in the interop does not expose this method. Is there any other way of doing it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.