· 6 years ago · Jan 03, 2020, 12:18 PM
1
2
3https://firebase.google.com/docs/functions/get-started
4
5firebase logout
6firebase login
7firebase init functions
8
9
10firebase list
11firebase use <project_id>
12
13
14Setup SendGrid
15
16// https://angularfirebase.com/lessons/sendgrid-v3-nodejs-transactional-email-cloud-function/
17// https://github.com/AngularFirebase/71-sendgrid-transactional-email-cloud-function/blob/master/functions/index.js
18
19cd functions
20npm install @sendgrid/mail --save
21npm install cors --save
22
23// create api key on send grid site
24firebase functions:config:set sendgrid.key=SG.YOUR_API_KEY
25
26// on point
27
28// set
29firebase functions:config:set sendgrid.key=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
30
31// get
32firebase functions:config:get
33
34// create template on send grid
35Hello {{userName}}
36You now have {{followerCount}} followers. Good work!
37https://github.com/sendgrid/sendgrid-nodejs/blob/master/packages/mail/USE_CASES.md
38
39
40
41firebase deploy --only functions
42firebase deploy --only functions:addMessage
43
44firebase deploy --only functions:sendAcceptEmail
45
46
47https://sendgrid.com/partners/google/
48https://github.com/firebase/functions-samples/blob/Node-8/quickstarts/email-users/functions/index.js
49
50
51https://github.com/firebase/functions-samples/blob/1c7c909ba6d3c5f999257b071f0ed8a77aaf3a42/quickstarts/email-users/functions/index.js
52
53
54// create function google using admin
55https://medium.com/google-cloud/sendgrid-email-automation-with-google-firestore-functions-30afcf7ac7aa
56
57
58
59email 1) welcome email when user signs up
60email 2) when an organizer invites you to a trip
61email 3) When a trip participant accepts a trip invite, organizer gets an email
62
63
64
65Networking
66https://github.com/AladinWay/NetworkingExample
67
68
69/*
70ios integration
71
72/*
73 var data: [Any] = []
74 let data1 = ["email": "atifsaeed14@gmail.com", "name": "Test", "trip": "lahore"]
75 data.append(data1)
76 let data2 = ["email": "atifsaeed14@gmail.com", "name": "Test 2", "trip": "karachi"]
77 data.append(data2)
78 print(data)
79
80 functions.httpsCallable("sendInviteEmail").call(data) { (result, error) in
81 if let error = error as NSError? {
82 if error.domain == FunctionsErrorDomain {
83 let code = FunctionsErrorCode(rawValue: error.code)
84 let message = error.localizedDescription
85 let details = error.userInfo[FunctionsErrorDetailsKey]
86 }
87 print(error.localizedDescription)
88 return
89 }
90 print(result?.data as? [String: Any] as Any)
91 // if let operationResult = (result?.data as? [String: Any])?["operationResult"] as? Int {
92 // self.resultField.text = "\(operationResult)"
93 // }
94 }
95
96
97 let data = ["email": "atifsaeed14@gmail.com", "name": "Abdul Basit Saeed", "trip": "USA"]
98 functions.httpsCallable("sendAcceptEmail").call(data) { (result, error) in
99 if let error = error as NSError? {
100 if error.domain == FunctionsErrorDomain {
101 let code = FunctionsErrorCode(rawValue: error.code)
102 let message = error.localizedDescription
103 let details = error.userInfo[FunctionsErrorDetailsKey]
104 }
105 print(error.localizedDescription)
106 return
107 }
108 print(result?.data as? Bool as Any)
109 if let result = (result?.data as? [String: Any])?["operationResult"] as? Bool {
110 print(result)
111 }
112 print(result?.data as? [String: Any] as Any)
113 if let operationResult = (result?.data as? [String: Any])?["operationResult"] as? Int {
114 self.resultField.text = "\(operationResult)"
115 }
116 } */
117
118*/
119
120
121// send welcome email when new node is added
122/*exports.sendWelcomeEmail = functions.firestore
123 .document('users/{userId}')
124 .onCreate((snap, context) => {
125
126 const user = snap.data()
127 const fullName = user.name
128 const emailAddress = user.email
129
130 const msg = {
131 // to: 'atifsaeed14@gmail.com',
132 to: emailAddress,
133 from: replay,
134 //subject: 'Hello world',
135 //text: 'Hello plain world!',
136 //html: '<p>Hello HTML world!</p>',
137 // custom templates
138 templateId: 'd-8a4719f02252447daff3ab3723168096',
139 dynamic_template_data: {
140 // custom properties
141 name: fullName,
142 // email: emailAddress
143 }
144 };
145
146 return sgMail.send(msg)
147 // .then(() => console.log('SendWelcomeEmail: ',emailAddress) )
148 // .catch(err => console.log('SendWelcomeEmail: ',err) )
149}); */
150
151
152/*
153//
154// Start writing Firebase Functions
155// https://firebase.google.com/docs/functions/typescript
156
157
158// https://us-central1-onpoint-2018.cloudfunctions.net/helloWorld
159// export const helloWorld = functions.https.onRequest((request, response) => {
160// response.send("Hello from Firebase!");
161// });
162
163
164// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
165// const functions = require('firebase-functions');
166
167// The Firebase Admin SDK to access the Firebase Realtime Database.
168//const admin = require('firebase-admin');
169admin.initializeApp(functions.config().firebase);
170
171
172// const cors = require('cors')({ origin: true });
173const SENDGRID_API_KEY = functions.config().sendgrid.key
174
175
176// const sgMail = require('@sendgrid/mail');
177sgMail.setApiKey(SENDGRID_API_KEY);
178*/
179
180// Helping link
181/*
182
183https://hightechtele.com/articles/firestore-trigger-email
184
185https://github.com/firebase/functions-samples/blob/Node-8/quickstarts/email-users/functions/index.js
186https://medium.com/google-cloud/sendgrid-email-automation-with-google-firestore-functions-30afcf7ac7aa
187https://github.com/firebase/quickstart-js/blob/a579893cfa33121952aeed9069c1554ed4e65b7e/functions/functions/index.js#L56-L103
188
189https://github.com/firebase/snippets-node/blob/20d7b8cdf8ee3e5ad5361adf4a2528840a10ffe5/firestore/extend-with-functions/functions/index.js#L150-L160
190
191
192https://www.taniarascia.com/promise-all-with-async-await/
193https://stackoverflow.com/questions/33073509/promise-all-then-resolve
194https://medium.com/dev-bits/writing-neat-asynchronous-node-js-code-with-promises-32ed3a4fd098
195
196
197
198exports.createUser = functions.firestore
199 .document('users/{userId}')
200 .onCreate((snap, context) => {
201 // Get an object representing the document
202 // e.g. {'name': 'Marie', 'age': 66}
203
204 const newValue = snap.data();
205 const name = newValue.name; // ?? ""
206
207 // access a particular field as you would any JS property
208 //if (name != null) {
209 console.log(name);
210 //}
211
212 // let newValue = snap.data()
213 // console.log("context: ")
214 // console.log(context)
215 // console.log("newValue: ")
216 // console.log(newValue)
217
218 // if (newValue['name'] != null) {
219 // const name = newValue['name']
220 // console.log(name)
221 // }
222 // access a particular field as you would any JS property
223 // const name = newValue["n"];
224 //console.log(newValue.name);
225 // perform desired operations ...
226
227
228
229 const msg = {
230 to: 'atifsaeed14@gmail.com',
231 from: 'noreplay@onpoints.com',
232 subject: 'New Follower',
233 // text: `Hey ${newValue.name}. You have a new follower!!! `,
234 //html: `<strong>Hey ${toName}. You have a new follower!!!</strong>`,
235
236 // custom templates
237 templateId: 'd-b8d21f90b7604c9fb74f02d3f3df52be',
238 //substitutionWrappers: ['{{', '}}'],
239 // substitutions: {
240 // name: 'Atif Saeed'
241 // }
242 dynamic_template_data: {
243 name: 'Atif Saeed'
244 // and other custom properties here
245 }
246 };
247
248 return sgMail.send(msg);
249
250 });
251
252
253exports.firestoreEmail = functions.firestore
254 .document('users/{userId}')
255 .onCreate(event => {
256
257 const userId = event.params.userId;
258
259 const db = admin.firestore()
260
261 // return db.collection('users').doc(userId)
262 // .get()
263 // .then(doc => {
264
265 // const user = doc.data()
266
267 // const msg = {
268 // to: user.email,
269 // from: 'hello@angularfirebase.com',
270 // subject: 'New Follower',
271 // // text: `Hey ${toName}. You have a new follower!!! `,
272 // // html: `<strong>Hey ${toName}. You have a new follower!!!</strong>`,
273
274 // // custom templates
275 // templateId: '300e1045-5b30-4f15-8c43-41754b73fe4f',
276 // substitutionWrappers: ['{{', '}}'],
277 // substitutions: {
278 // name: user.displayName
279 // // and other custom properties here
280 // }
281 // };
282
283 // return sgMail.send(msg)
284 // })
285 // .then(() => console.log('email sent!') )
286 // .catch(err => console.log(err) )
287
288
289});
290
291
292
293
294//functions.auth.user().onCreate((user) => {
295exports.sendWelcomeEmail = functions.auth.user().onCreate((user) => {
296 // const creationTime = userRecord.metadata.creationTime; // 2016-12-15T19:37:37.059Z
297 // const lastSignInTime = userRecord.metadata.lastSignInTime; // 2018-01-03T16:23:12.051Z
298// const email = userRecord.email; // The email of the user.
299// const displayName = userRecord.displayName; // The display name of the user.
300 // [END eventAttributes]
301 const email = user.email; // The email of the user.
302 const displayName = user.displayName; // The display name of the user.
303 console.log(email)
304 console.log(displayName)
305
306
307
308 const msg = {
309 to: ['atifsaeed14@gmail.com'],
310 from: 'noreplay@onpoints.com',
311 subject: 'New Follower',
312 // text: `Hey ${toName}. You have a new follower!!! `,
313 // html: `<strong>Hey ${toName}. You have a new follower!!!</strong>`,
314
315 // custom templates
316 templateId: 'd-8a4719f02252447daff3ab3723168096',
317 substitutionWrappers: ['{{', '}}'],
318 substitutions: {
319 name: 'Atif Saeed'
320 // and other custom properties here
321 }
322};
323
324return sgMail.send(msg)
325
326 // .then(() => res.status(200).send('email sent!') )
327 // .catch(err => res.status(400).send(err) )
328
329});
330
331*/
332 //});
333
334
335// [START sendWelcomeEmail]
336/**
337 * Sends a welcome email to new user.
338 */
339// [START onCreateTrigger]
340/*
341exports.sendWelcomeEmail = functions.auth.user().onCreate((user) => {
342 // [END onCreateTrigger]
343 // [START eventAttributes]
344 const email = user.email; // The email of the user.
345 const displayName = user.displayName; // The display name of the user.
346 // [END eventAttributes]
347
348 return sendWelcomeEmail(email, displayName);
349 });
350 // [END sendWelcomeEmail]
351
352
353
354exports.httpEmail = functions.https.onRequest((req, res) => {
355
356 cors( req, res, () => {
357
358 const toName = req.body.toName;
359 const toEmail = req.body.toEmail;
360
361 const msg = {
362 to: toEmail,
363 from: 'hello@angularfirebase.com',
364 subject: 'New Follower',
365 // text: `Hey ${toName}. You have a new follower!!! `,
366 // html: `<strong>Hey ${toName}. You have a new follower!!!</strong>`,
367
368 // custom templates
369 templateId: '300e1045-5b30-4f15-8c43-41754b73fe4f',
370 substitutionWrappers: ['{{', '}}'],
371 substitutions: {
372 name: toName
373 // and other custom properties here
374 }
375 };
376
377 return sgMail.send(msg)
378
379 .then(() => res.status(200).send('email sent!') )
380 .catch(err => res.status(400).send(err) )
381
382 });
383
384});
385
386
387
388exports.firestoreEmail = functions.firestore
389 .document('users/{userId}/followers/{followerId}')
390 .onCreate(event => {
391
392 const userId = event.params.userId;
393
394 const db = admin.firestore()
395
396 return db.collection('users').doc(userId)
397 .get()
398 .then(doc => {
399
400 const user = doc.data()
401
402 const msg = {
403 to: user.email,
404 from: 'hello@angularfirebase.com',
405 subject: 'New Follower',
406 // text: `Hey ${toName}. You have a new follower!!! `,
407 // html: `<strong>Hey ${toName}. You have a new follower!!!</strong>`,
408
409 // custom templates
410 templateId: '300e1045-5b30-4f15-8c43-41754b73fe4f',
411 substitutionWrappers: ['{{', '}}'],
412 substitutions: {
413 name: user.displayName
414 // and other custom properties here
415 }
416 };
417
418 return sgMail.send(msg)
419 })
420 .then(() => console.log('email sent!') )
421 .catch(err => console.log(err) )
422
423
424});
425
426email 1) welcome email when user signs up
427email 2) when an organizer invites you to a trip
428email 3) When a trip participant accepts a trip invite, organizer gets an email
429
430export const accountCreate = functions.auth.user().onCreate(user => {
431 console.log(user.data);
432 userDoc = {'email' = user.data.email,
433 'displayName' = user.data.displayName}
434 admin.firestore().collection('users').doc(user.data.uid)
435 .set(userDoc).then(writeResult => {
436 console.log('User Created result:', writeResult);
437 return;
438 }).catch(err => {
439 console.log(err);
440 return;
441 });
442});
443
444
445lazy var functions = Functions.functions()
446
447
448 func didTapAdd() {
449 // [START function_add_numbers]
450 //let data = ["firstNumber": Int(number1Field.text!),
451 // "secondNumber": Int(number2Field.text!)]
452// let
453// var data = [String:String]()
454// data["email"] = "test@gmail.com"
455// data["name"] = "test"
456
457 var data: [Any] = []
458 let data1 = ["email": "test@gmail.com", "name": "Test", "trip": "lahore"]
459 data.append(data1)
460 let data2 = ["email": "test2@gmail.com", "name": "Test 2", "trip": "karachi"]
461 data.append(data2)
462 print(data)
463
464 functions.httpsCallable("sendInviteEmail").call(data) { (result, error) in
465 if let error = error as NSError? {
466 if error.domain == FunctionsErrorDomain {
467 let code = FunctionsErrorCode(rawValue: error.code)
468 let message = error.localizedDescription
469 let details = error.userInfo[FunctionsErrorDetailsKey]
470 }
471 print(error.localizedDescription)
472 return
473 }
474 print(result?.data as? [String: Any] as Any)
475 // if let operationResult = (result?.data as? [String: Any])?["operationResult"] as? Int {
476 // self.resultField.text = "\(operationResult)"
477 // }
478 }
479 /*
480 let data = ["email": "test@gmail.com", "name": "Test", "trip": "lahore"]
481
482 functions.httpsCallable("").call(<#T##data: Any?##Any?#>) { (<#HTTPSCallableResult?#>, <#Error?#>) in
483 <#code#>
484 }
485
486 functions.httpsCallable("sendAcceptEmail").call(data) { (result, error) in
487 if let error = error as NSError? {
488 if error.domain == FunctionsErrorDomain {
489 let code = FunctionsErrorCode(rawValue: error.code)
490 let message = error.localizedDescription
491 let details = error.userInfo[FunctionsErrorDetailsKey]
492 }
493 print(error.localizedDescription)
494 return
495 }
496 print(result?.data as? [String: Any] as Any)
497// if let operationResult = (result?.data as? [String: Any])?["operationResult"] as? Int {
498// self.resultField.text = "\(operationResult)"
499// }
500 }
501
502
503
504
505 }
506
507*/