11/**
2- * Copyright 2016 , Google, Inc .
2+ * Copyright 2019 , Google LLC .
33 * Licensed under the Apache License, Version 2.0 (the "License");
44 * you may not use this file except in compliance with the License.
55 * You may obtain a copy of the License at
1515
1616'use strict' ;
1717
18- const format = require ( 'util' ) . format ;
1918const express = require ( 'express' ) ;
2019const bodyParser = require ( 'body-parser' ) . urlencoded ( {
2120 extended : false ,
@@ -33,12 +32,14 @@ if (!TWILIO_NUMBER) {
3332 ) ;
3433}
3534
36- const twilio = require ( 'twilio' ) (
35+ const Twilio = require ( 'twilio' ) ;
36+
37+ const twilioClient = Twilio (
3738 process . env . TWILIO_ACCOUNT_SID ,
3839 process . env . TWILIO_AUTH_TOKEN
3940) ;
4041
41- const TwimlResponse = require ( 'twilio' ) . TwimlResponse ;
42+ const TwimlResponse = Twilio . TwimlResponse ;
4243
4344// [START gae_flex_twilio_receive_call]
4445app . post ( '/call/receive' , ( req , res ) => {
@@ -53,7 +54,7 @@ app.post('/call/receive', (req, res) => {
5354// [END gae_flex_twilio_receive_call]
5455
5556// [START gae_flex_twilio_send_sms]
56- app . get ( '/sms/send' , ( req , res , next ) => {
57+ app . get ( '/sms/send' , async ( req , res , next ) => {
5758 const to = req . query . to ;
5859 if ( ! to ) {
5960 res
@@ -62,20 +63,18 @@ app.get('/sms/send', (req, res, next) => {
6263 return ;
6364 }
6465
65- twilio . sendMessage (
66- {
66+ try {
67+ await twilioClient . messages . create ( {
6768 to : to ,
6869 from : TWILIO_NUMBER ,
6970 body : 'Hello from Google App Engine' ,
70- } ,
71- err => {
72- if ( err ) {
73- next ( err ) ;
74- return ;
75- }
76- res . status ( 200 ) . send ( 'Message sent.' ) ;
77- }
78- ) ;
71+ } ) ;
72+ console . log ( 'BAZ!' ) ;
73+ res . status ( 200 ) . send ( 'Message sent.' ) ;
74+ } catch ( err ) {
75+ next ( err ) ;
76+ return ;
77+ }
7978} ) ;
8079// [END gae_flex_twilio_send_sms]
8180
@@ -85,7 +84,7 @@ app.post('/sms/receive', bodyParser, (req, res) => {
8584 const body = req . body . Body ;
8685
8786 const resp = new TwimlResponse ( ) ;
88- resp . message ( format ( ' Hello, %s , you said: %s' , sender , body ) ) ;
87+ resp . message ( ` Hello, ${ sender } , you said: ${ body } ` ) ;
8988
9089 res
9190 . status ( 200 )
@@ -95,8 +94,12 @@ app.post('/sms/receive', bodyParser, (req, res) => {
9594// [END gae_flex_twilio_receive_sms]
9695
9796// Start the server
98- const PORT = process . env . PORT ;
99- app . listen ( PORT , ( ) => {
100- console . log ( `App listening on port ${ PORT } ` ) ;
101- console . log ( 'Press Ctrl+C to quit.' ) ;
102- } ) ;
97+ if ( module === require . main ) {
98+ const PORT = process . env . PORT || 8080 ;
99+ app . listen ( PORT , ( ) => {
100+ console . log ( `App listening on port ${ PORT } ` ) ;
101+ console . log ( 'Press Ctrl+C to quit.' ) ;
102+ } ) ;
103+ }
104+
105+ exports . app = app ;
0 commit comments