Google Cloud Platform Node.js Library
I am creating a google function. However, when I try to deploy to Google Cloud Platform, I am getting this error
ERROR: (gcloud.beta.functions.deploy) OperationError: code=3, message=Function load error: Code in file index.js can't be loaded. Did you list all required modules in the package.json dependencies? Detailed stack trace: Error: Cannot find module 'request'
How do I upload/install the 'request' library in google cloud platform?
Code Snippet
'use strict';
const https = require('https');
const host = 'https://www.example.com';
const clientId = 'qpopMIGtVdeIdVk3oEtr2LGbn8vTeTWz';
const clientSecret = 'eUnsWQ8y3AuiFHJu';
const grant_type = 'client_credentials';
const resource = 'b.microsoft.com/4fa4b4a7-d34f-49af-8781-c8b39f0cf770';
const request = require("request");
exports.oauthtoken = (req, res) => {
// Call the Apigee API
callGetOAuthToken().then((output) => {
// Return the results from the APigee to DialogFlow
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ 'speech': output, 'displayText': output }));
}).catch((error) => {
// If there is an error let the user know
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ 'speech': error, 'displayText': error }));
});
};
function callGetOAuthToken () {
return new Promise((resolve, reject) => {
let path = '/customers/v1/accesstoken';
var authHeader = Buffer.from(clientId + ':' + clientSecret).toString('base64');
var post_options = {
url: host + path,
method: 'POST',
headers:
{
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + authHeader,
'grant_type':grant_type
}
};
// Make the HTTP request to get the weather
request(post_options, function(err, res, body) {
let output = JSON.parse(body);
console.log(output);
resolve(output);
});
});
}
-Alan-
1 answer
-
answered 2018-04-17 05:59
ansibly
Read through the Google Cloud documentation regarding dependencies: https://cloud.google.com/functions/docs/writing/dependencies
List the 'request' module as a dependency in your package.json file if using the gcloud CLI.
Or, run 'npm install --save request' in the folder containing your cloud function and upload your pre-installed dependencies as part of your ZIP file.
See also questions close to this topic
-
API for getting medicine details
I am creating an app in which user will be able to order medicines. For that purpose I need a database in which if I input barcode or name or chemical name of medicine (any one parameter), it will return all other parameters. Like in case of entering barcode info, it should return name, chemical formula price etc. Moreover I need a database which should have the medicines used in GCC (Bahrain, UAE, Oman etc) I have searched and came across a few but they are not of much use to me because either they are too expensive or belong to USA or Canada.
Any help would be appreciated. Thanks in advance.
-
Babel plugin "transform-runtime" only works after first compile
I have a very perplexing issue with Babel.
When I run
yarn run dev
, I get the following error:(function (exports, require, module, __filename, __dirname) { import _slicedToArray from "babel-runtime/helpers/slicedToArray"; ^^^^^^ SyntaxError: Unexpected token import at createScript (vm.js:74:10) at Object.runInThisContext (vm.js:116:10) at Module._compile (module.js:537:28) at loader (/home/raphael/workspace/yopp/fo/node_modules/babel-register/lib/node.js:144:5) at Object.require.extensions.(anonymous function) [as .js] (/home/raphael/workspace/yopp/fo/node_modules/babel-register/lib/node.js:154:7) at Module.load (module.js:507:32) at tryModuleLoad (module.js:470:12) at Function.Module._load (module.js:462:3) at Module.require (module.js:517:17) at require (internal/module.js:11:18)
but if I remove
transform-runtime
from my plugins in.babelrc
, wait for it to compile then add it back, it'll compile and function correctly.Here is my
.babelrc
:{ "presets": [ [ "env", { "targets": { "browsers": [ "> 1% in FR", "safari >= 10" ] }, "modules": false } ], "react", "flow" ], "plugins": [ "transform-object-rest-spread", "transform-class-properties", "transform-runtime", "react-hot-loader/babel" ], "env": { "test": { "presets": [ [ "env", { "modules": "commonjs" } ], "react", "flow" ], "plugins": [ "transform-object-rest-spread", "transform-class-properties", "transform-runtime", "react-hot-loader/babel" ] } } }
-
CHILD_PROCESS , DGRAM , DEFAULTABLE.js
can you help me please with this errors : I want to connect to a locally ip by ssh and i cant because i don't have the libraries , i tried to download them but they're empty .
WARNING in ./node_modules/defaultable/defaultable.js
49:13-31 Critical dependency: the request of a dependency is an expression
ERROR in ./node_modules/simple-ssh/node_modules/ssh2/lib/agent.js
Module not found: Error: Can't resolve 'child_process' in '/home/mehdi/Escritorio/Login2/node_modules/simple-ssh/node_modules/ssh2/lib'
ERROR in ./node_modules/native-dns-cache/lookup.js
Module not found: Error: Can't resolve 'dgram' in '/home/mehdi/Escritorio/Login2/node_modules/native-dns-cache'
ERROR in ./node_modules/native-dns/lib/server.js
Module not found: Error: Can't resolve 'dgram' in '/home/mehdi/Escritorio/Login2/node_modules/native-dns/lib'
ERROR in ./node_modules/native-dns/lib/utils.js
Module not found: Error: Can't resolve 'dgram' in '/home/mehdi/Escritorio/Login2/node_modules/native-dns/lib'
Thank you very Much.
-
P2 OAuth2 Daylight Savings check
I'm trying to perform a manual check on an access tokens expiry when Daylight Savings time is detected on the client. Under P2OAuth2 the token expiry gets set using
Date(timeIntervalSinceNow: expires)
- expires being the value 3600. The problem is that I'm in Daylight savings where the time is +1 hour and this is throwing out the token expiry. Xcode sim is running under Europe/London region but the time is still -1 hour behind the current. Is there a known way I can solve this, a global daylight savings change?I'm currently using this approach:
public var isLoggedIn: Bool { get { let tz = TimeZone.current if tz.isDaylightSavingTime() { print("DST detected") if let expiry = oauth2.accessTokenExpiry { let DstDate = Date().addingTimeInterval(TimeInterval(3600)) print("DST DATE: \(DstDate)") let dstResult = (.orderedDescending == expiry.compare(DstDate)) if dstResult == false { oauth2.accessToken = nil return false } } } return oauth2.hasUnexpiredAccessToken() || oauth2.refreshToken != nil } }
I can't change the value inside the pod library
Thanks
-
com.google.HTTPStatus error 400 - cordova ios
this is really hard to debug. GooglePlus plugin fails at login on a iOS simulator error logged => The operation couldn’t be completed. (com.google.HTTPStatus error 400.)
this is my config.xml in Ionic App :
<?xml version='1.0' encoding='utf-8'?> <widget id="com.auth-firebase-5" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> <name>com.auth-firebase-5</name> <description>An awesome Ionic/Cordova app.</description> <author email="hi@ionicframework" href="http://ionicframework.com/">Ionic Framework Team</author> <content src="index.html" /> <access origin="*" /> <allow-intent href="http://*/*" /> <allow-intent href="https://*/*" /> <allow-intent href="tel:*" /> <allow-intent href="sms:*" /> <allow-intent href="mailto:*" /> <allow-intent href="geo:*" /> <preference name="ScrollEnabled" value="false" /> <preference name="android-minSdkVersion" value="19" /> <preference name="BackupWebStorage" value="none" /> <preference name="SplashMaintainAspectRatio" value="true" /> <preference name="FadeSplashScreenDuration" value="300" /> <preference name="SplashShowOnlyFirstTime" value="false" /> <preference name="SplashScreen" value="screen" /> <preference name="SplashScreenDelay" value="3000" /> <platform name="android"> <allow-intent href="market:*" /> <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png" /> <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png" /> <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png" /> <icon density="xhdpi" src="resources/android/icon/drawable-xhdpi-icon.png" /> <icon density="xxhdpi" src="resources/android/icon/drawable-xxhdpi-icon.png" /> <icon density="xxxhdpi" src="resources/android/icon/drawable-xxxhdpi-icon.png" /> <splash density="land-ldpi" src="resources/android/splash/drawable-land-ldpi-screen.png" /> <splash density="land-mdpi" src="resources/android/splash/drawable-land-mdpi-screen.png" /> <splash density="land-hdpi" src="resources/android/splash/drawable-land-hdpi-screen.png" /> <splash density="land-xhdpi" src="resources/android/splash/drawable-land-xhdpi-screen.png" /> <splash density="land-xxhdpi" src="resources/android/splash/drawable-land-xxhdpi-screen.png" /> <splash density="land-xxxhdpi" src="resources/android/splash/drawable-land-xxxhdpi-screen.png" /> <splash density="port-ldpi" src="resources/android/splash/drawable-port-ldpi-screen.png" /> <splash density="port-mdpi" src="resources/android/splash/drawable-port-mdpi-screen.png" /> <splash density="port-hdpi" src="resources/android/splash/drawable-port-hdpi-screen.png" /> <splash density="port-xhdpi" src="resources/android/splash/drawable-port-xhdpi-screen.png" /> <splash density="port-xxhdpi" src="resources/android/splash/drawable-port-xxhdpi-screen.png" /> <splash density="port-xxxhdpi" src="resources/android/splash/drawable-port-xxxhdpi-screen.png" /> </platform> <platform name="ios"> <allow-intent href="itms:*" /> <allow-intent href="itms-apps:*" /> <icon height="57" src="resources/ios/icon/icon.png" width="57" /> <icon height="114" src="resources/ios/icon/icon@2x.png" width="114" /> <icon height="40" src="resources/ios/icon/icon-40.png" width="40" /> <icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" /> <icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" /> <icon height="50" src="resources/ios/icon/icon-50.png" width="50" /> <icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" /> <icon height="60" src="resources/ios/icon/icon-60.png" width="60" /> <icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" /> <icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" /> <icon height="72" src="resources/ios/icon/icon-72.png" width="72" /> <icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" /> <icon height="76" src="resources/ios/icon/icon-76.png" width="76" /> <icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" /> <icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" /> <icon height="29" src="resources/ios/icon/icon-small.png" width="29" /> <icon height="58" src="resources/ios/icon/icon-small@2x.png" width="58" /> <icon height="87" src="resources/ios/icon/icon-small@3x.png" width="87" /> <icon height="1024" src="resources/ios/icon/icon-1024.png" width="1024" /> <splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" /> <splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" /> <splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" /> <splash height="1242" src="resources/ios/splash/Default-Landscape-736h.png" width="2208" /> <splash height="1536" src="resources/ios/splash/Default-Landscape@2x~ipad.png" width="2048" /> <splash height="2048" src="resources/ios/splash/Default-Landscape@~ipadpro.png" width="2732" /> <splash height="768" src="resources/ios/splash/Default-Landscape~ipad.png" width="1024" /> <splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" /> <splash height="2732" src="resources/ios/splash/Default-Portrait@~ipadpro.png" width="2048" /> <splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" /> <splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" /> <splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" /> <splash height="2732" src="resources/ios/splash/Default@2x~universal~anyany.png" width="2732" /> </platform> <universal-links> <host name="https://q8upt.app.goo.gl" scheme="https" /> <host name="ionicangularfireapp.firebaseapp.com" scheme="https"> <path url="/__/auth/callback" /> </host> <content src="index.html" /> </universal-links> <engine name="browser" spec="5.0.3" /> <plugin name="cordova-plugin-facebook4" spec="^1.10.1"> <variable name="APP_ID" value="156344898369807" /> <variable name="APP_NAME" value="IONICangularFireApp" /> </plugin> <plugin name="cordova-plugin-whitelist" spec="^1.3.3" /> <plugin name="cordova-plugin-device" spec="^2.0.1" /> <plugin name="cordova-plugin-splashscreen" spec="^5.0.2" /> <plugin name="cordova-plugin-ionic-webview" spec="^1.2.0" /> <plugin name="cordova-plugin-ionic-keyboard" spec="^2.0.5" /> <plugin name="https://github.com/EddyVerbruggen/cordova-plugin-googleplus.git" spec="^5.2.3"> <variable name="REVERSED_CLIENT_ID" value="com.googleusercontent.apps.558165536676-q8e18bb4uc1mtipjut6qpjn2epa741ep" /> <variable name="WEB_APPLICATION_CLIENT_ID" value="1043269342338-4epn9c4rgs881sjjnb3kvh5snhae1j70.apps.googleusercontent.com" /> </plugin> <engine name="ios" spec="~4.5.4" /> </widget>
configuration file config.ts with reference to CLIENT_ID and WEB_CLIENT_ID
export class Config { public static FIREBASE_CONFIG = { apiKey: "AIzaSyBDQeqhOoCOvQaBBHfEx0wJPLx5iwMQujU", authDomain: "ionicangularfireapp.firebaseapp.com", // or custom domain databaseURL: "https://ionicangularfireapp.firebaseio.com", projectId: "ionicangularfireapp", storageBucket: "ionicangularfireapp.appspot.com", messagingSenderId: "558165536676" }; public static CLIENT_ID = '1043269342338-5h0ssja1ft9ctpqojj8vsvgismahf1s6.apps.googleusercontent.com' public static WEB_CLIENT_ID = '1043269342338-4epn9c4rgs881sjjnb3kvh5snhae1j70.apps.googleusercontent.com'; }
I am not sure what I am missing thanks for the help because no other discussions could help
-
API Callback_URL Invalid Calls
I just started working with the Strava API on Android. In order to use it, I first need to successfully set up OAuth2. For this, I chose to use the Scribe library, since I have used it in a previous implementation.
Authentication happens in onCreate() method of the MainActivity. The test application uses two classes next to the MainActivity. StravaOAuth20ServiceImpl is for configuring the API requests for token and revoking of the token. StravaOAuth2Api contains the EndPoints for the API. These look ok.
I am not getting a code back from the callback. That's where I am stuck. In order to function, the callback needs to be set up correctly in Developer Settings for Strava, Android Manifest and the API EndPoint call.
I am currently working in Development Mode.. On the website it is stated that "
localhost
and127.0.0.1
are white-listed", so I have used these in my callback_url. For both I get the following JSON as a response:{ "message": "Bad Request", "errors": [ { "resource": "Application", "field": "redirect_uri", "code": "invalid" } ] }
So both these calls are invalid..
- https://www.strava.com/oauth/authorize?response_type=code&client_id=25016&redirect_uri=127.0.0.1 - https://www.strava.com/oauth/authorize?response_type=code&client_id=25016&redirect_uri=localhost
A related Question is about the form of the callback_url. I have done the same for FitBit and have used a callback in the form "http://callback_myapplication". In order to do so, I have to set up a "host" and "scheme" in my Android Manifest (see code underneath). When I try to do so in my application settings, I get an error message "Field has to be a domain, without //" (see print screen underneath). This is the first time I see this. Is it the callback without "scheme" then?
<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> <data android:host="127.0.0.1" android:scheme="http"/> </intent-filter>
Thank you on beforehand for your help!
-
GCP deployment manager same resource name in different deployment
To figure out how deployment manager behaves when we have same resource name in different deployment I did following steps:
- I create a deployment named dep-1 with single VM named vm1.
- Then I created a a deployment named dep-2 with same VM named vm1.
I was thinking that dep-2 will fail saying a resource already exist with same name but it succeeded without any warning/error.
Later when I deleted dep-2 it deleted the vm resource named vm-1.
Now I want to know how to deal with this behavior. Say I want to deploy my environment for dev, qa and prod. What is the best practice to do it in GCP deployment manager?
-
Google Cloud SQL instance connection error
I set up GCP for App Maker and create instance and make a connection but there's an ERROR: Cannot create admin user in the default Google Cloud SQL instance. How to address this issue? TIA
-
gcloud beta projects move some-project-id --organization=0
We created a project in the Google Cloud Console and it added it to an organization. We need to move this project to another organization where our other projects are.
We are trying to move it with this gcloud command but we get an error.
$ gcloud beta projects move some-project-id --organization=0
ERROR: (gcloud.beta.projects.move) INVALID_ARGUMENT: field [Project.parent] has issue [Project parent cannot be empty.] - '@type': type.googleapis.com/google.rpc.BadRequest fieldViolations: - description: Project parent cannot be empty. field: Project.parent
https://cloud.google.com/sdk/gcloud/reference/beta/projects/move
-
Possible to update the field in below datastructure in firestore database using cloud funct
I have a datastructure in the form of object structure .
I have a condition when whose Invite(1,2,3) PhoneNumber matches with other document that invitee need to update the field as Status = true
When I try to update a field as Status = true It is updating at the end of the document.Please if their is any approach help with me. Thanks
-
Firestore cloud function, add author's UID to document creation
When one of my users creates a specific document, for example a post, I would like to add its UID to the document.
I tried to find a way to achieve that through cloud functions and the onCreate trigger, but it seems that the user's UID isn't reachable within those function.
exports.createPublication = functions.firestore .document('publications/{publication}') .onCreate((snap, context) => { const newValue = snap.data(); return snapshot.ref.child('authorId').set("ID"); });
I was really suprised that Firestore doesn't add natively a AuthorId field like others databases would do (Mongo, Parse, etc...) Of course, I can add this UID from the client, but I think it is a bit dirty.
-
Is there a way to use an additional command line app in firebase functions?
I am currently developing a web app using the firebase cloud function. I found an example using a command line app. of looking at functions-examples.
The above example creates a thumbnail image using ImageMagic installed by default in the cloud function.
I thought I could run the command line app by looking at the code below.
return spawn ('convert', [tempLocalFile, '-thumbnail', `$ {THUMB_MAX_WIDTH} x $ {THUMB_MAX_HEIGHT}`, tempLocalThumbFile], {capture: ['stdout', 'stderr']});
So now I would like to use the command line app called decktape in the cloud function to convert the html file to pdf. However, When I try to run this app's command,
permission denied
appear. Is there a way to use this decktape app?