Skip to content

Instantly share code, notes, and snippets.

@CodingDoug
Last active November 6, 2022 09:29
Show Gist options
  • Star 40 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save CodingDoug/814a75ff55d5a3f951f8a7df3979636a to your computer and use it in GitHub Desktop.
Save CodingDoug/814a75ff55d5a3f951f8a7df3979636a to your computer and use it in GitHub Desktop.
Example code from the video "Use async/await with TypeScript in Cloud Functions"

Example code from the video "Use async/await with TypeScript in Cloud Functions"

This is the example code from my video about using async/await with Cloud Functions. I've placed it here in a gist so it's easier to compare the "before" and "after" states for each case.

Watch the video here

The code in this project is licensed under the Apache License 2.0.

Copyright 2018 Google LLC
 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
    https://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.
export const getBostonWeather = functions.https.onRequest((request, response) => {
admin.firestore().doc("cities-weather/boston-ma-us").get()
.then(snapshot => {
const data = snapshot.data()
response.send(data)
})
.catch(error => {
// Handle the error
console.log(error)
response.status(500).send(error)
})
})
export const getBostonWeather = functions.https.onRequest(async (request, response) => {
try {
const snapshot = await admin.firestore().doc("cities-weather/boston-ma-us").get()
const data = snapshot.data()
response.send(data)
}
catch (error) {
// Handle the error
console.log(error)
response.status(500).send(error)
}
})
export const getBostonAreaWeather = functions.https.onRequest((request, response) => {
admin.firestore().doc("areas/greater-boston").get()
.then(areaSnapshot => {
const cities = areaSnapshot.data().cities
const promises = []
cities.forEach(city => {
const p = admin.firestore().doc(`cities-weather/${city}`).get()
promises.push(p)
})
return Promise.all(promises)
})
.then(snapshots => {
const results = []
snapshots.forEach(snap => {
const data = snap.data()
data.city = snap.id
results.push(data)
})
response.send(results)
})
.catch(error => {
console.log(error)
response.status(500).send(error)
})
})
export const getBostonAreaWeather = functions.https.onRequest(async (request, response) => {
try {
const areaSnapshot = await admin.firestore().doc("areas/greater-boston").get()
const cities = areaSnapshot.data().cities
const promises = []
cities.forEach(city => {
const p = admin.firestore().doc(`cities-weather/${city}`).get()
promises.push(p)
})
const snapshots = await Promise.all(promises)
const results = []
snapshots.forEach(snap => {
const data = snap.data()
data.city = snap.id
results.push(data)
})
response.send(results)
}
catch (error) {
console.error(error)
response.status(500).send(error)
}
})
@robmontesinos
Copy link

Thank you Doug!!

@DevilWarrior
Copy link

Hi,

When adding the async key to the function I get the error below, any ideas?

!  functions[process_payment(us-central1)]: Deployment error.
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /user_code/index.js:65
exports.mailReceived = functions.https.onRequest( async (req, res) => {
                                                        ^

SyntaxError: Unexpected token (
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at getUserFunction (/var/tmp/worker/worker.js:388:24)

@DevilWarrior
Copy link

Never mind, It seems to be a discrepancy with node, let me update to the correct version.

@conormcelvaney
Copy link

Doug you are a legend, love your stuff, have just taken on Typescript because of your encouragement !

@predorock
Copy link

@devil

Never mind, It seems to be a discrepancy with node, let me update to the correct version.

Hi, I have the same problem with node, how do you fix it?

@quaternioninterpolation
Copy link

Incredible cheers

@ykabbara
Copy link

#Error

  • "Object is possibly 'undefined'.ts(2532)" error on line 9
  • "Variable 'results' implicitly has type 'any[]' in some locations where its type cannot be determined.ts(7034)" error on line 17
    and
  • "Variable 'results' implicitly has an 'any[]' type.ts(7005)" on line 23
    Anyone have the same problem or can help?

@Marcus-C137
Copy link

I'm having the same problem can't find a fix

@andrsdev
Copy link

andrsdev commented Apr 13, 2019

@Marcus-C137 for this to work you have to change these files in /functions directory to use ECMAScript2017

in .eslintrc.json

 "parserOptions": {
    // Required for certain syntax usages
    "ecmaVersion": 8
  },

and in package.json add

  "engines": {
    "node": "8"
  },

And then run npm install --save

@MeStrak
Copy link

MeStrak commented May 11, 2019

@Marcus-C137 @ykabbara

I must admit that I haven't tested this, but I think you can fix it by defining the type in the array. From the code it looks like it should be an array of DocumentData objects.

add this import to index.ts if you don't have it to get firebase types:

import * as firebase from 'firebase';
And edit package.json to add in the firebase reference so it looks something like the following:

"dependencies": {`
   "firebase-admin": "~7.0.0",
   "firebase-functions": "^2.2.0",
   **"firebase": "^6.0.2"**
 },

Then edit the line where const results is created to read
const results: firebase.firestore.DocumentData [] = []

Like I said I didn't test this, so I'm not certain that DocumentData is the correct object type, You should be able to check it by calling typeof, and you can see the list in this doc: https://firebase.google.com/docs/reference/js/firebase.firestore.html.

I had a similar issue on my project when trying to pass a snapshot into an arrow function and fixed it by adding the type to the snapshot:
.then( (snapshot: firebase.firestore.QuerySnapshot) => {}

I hope that helps you and this isn't a red herring!

@choiseonjae
Copy link

Hey... I think you need to update the code. 'cause I'm also having trouble with the problem as same as above.
I can't fix the error 'ts2532'

@vinod-hosamani
Copy link

export const getBostonAreaWeather = functions.https.onRequest((request, response) => {
admin.firestore().doc("areas/greater-boston").get()
.then(areaSnapshot => {
const cities = areaSnapshot.data().cities
const promises: any[] | never[] | Promise<FirebaseFirestore.DocumentSnapshot>[] = []
cities.forEach((city: any) => {
const p = admin.firestore().doc(cities-weather/${city}).get()
promises.push(p)
})
return Promise.all(promises)
})
.then(snapshots => {
const results: any[] | never[] = []
snapshots.forEach(snap => {
const data = snap.data()
data.city = snap.id
results.push(data)
})
response.send(results)
})
.catch(error => {
console.log(error)
response.status(500).send(error)
})
})

Hi sir
I am getting six errors in this code ,its not working in my vs code its showing 6 errors
I think you have to update the code please help me

@vinod-hosamani
Copy link

here is my error

src/index.ts:17:24 - error TS2532: Object is possibly 'undefined'.

17 const cities = areaSnapshot.data().cities
~~~~~~~~~~~~~~~~~~~

src/index.ts:18:15 - error TS7034: Variable 'promises' implicitly has type 'any[]' in some locations where its type cannot be determined.

18 const promises = []
~~~~~~~~

src/index.ts:19:24 - error TS7006: Parameter 'city' implicitly has an 'any' type.

19 cities.forEach(city => {
~~~~

src/index.ts:24:45 - error TS7005: Variable 'promises' implicitly has an 'any[]' type.

24 const snapshots = await Promise.all(promises)
~~~~~~~~

src/index.ts:26:15 - error TS7034: Variable 'results' implicitly has type 'any[]' in some locations where its type cannot be determined.

26 const results = []
~~~~~~~

src/index.ts:33:23 - error TS7005: Variable 'results' implicitly has an 'any[]' type.

33 response.send(results)
~~~~~~~

Found 6 errors.

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! functions@ build: tsc
npm ERR! Exit status 2
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.

@ralbertini
Copy link

to ignore errors like ' Object is possibly 'undefined'.' :
go to tsconfig.json and add "strictNullChecks":false

@tkhduracell
Copy link

I'm missing examples with pubsub topics.

@BoHuang2018
Copy link

BoHuang2018 commented Apr 20, 2020

@vinod-hosamani @tkhduracell
I had the same errors with you, and fixed them with the following steps.

Step 1. To configure the file "functions/tsconfig.json" :
disable the line : "strict": true, ( in compilerOptions {...} )
enable a new option: "noImplicitAny": false (in compilerOptions {...} )
add a new line: "strictNullChecks":false. ( after "include": ["src"],)

Step 2. In the command line, run "npm install -g tslint"

Step 3. in the command line, run "npm run-script build "

After the step 1, the new file "functions/tsconfig.json" should be like
{ "compilerOptions": { "module": "commonjs", "noImplicitReturns": true, "noUnusedLocals": true, "outDir": "lib", "sourceMap": true, // "strict": true, "target": "es2017", "noImplicitAny": false }, "compileOnSave": true, "include": [ "src" ], "strictNullChecks":false }

@brikiernan
Copy link

@vinod-hosamani @tkhduracell
I had the same errors with you, and fixed them with the following steps.

Step 1. To configure the file "functions/tsconfig.json" :
disable the line : "strict": true, ( in compilerOptions {...} )
enable a new option: "noImplicitAny": false (in compilerOptions {...} )
add a new line: "strictNullChecks":false. ( after "include": ["src"],)

Step 2. In the command line, run "npm install -g tslint"

Step 3. in the command line, run "npm run-script build "

After the step 1, the new file "functions/tsconfig.json" should be like
{ "compilerOptions": { "module": "commonjs", "noImplicitReturns": true, "noUnusedLocals": true, "outDir": "lib", "sourceMap": true, // "strict": true, "target": "es2017", "noImplicitAny": false }, "compileOnSave": true, "include": [ "src" ], "strictNullChecks":false }

@BoHuang2018 This worked for me!! 60 mins of fussing and just needed a config tweak... lol

@knifewine
Copy link

Just wanted to say I stumbled on this code and it was a great help to unblock me in a project. Thank you! 🥇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment