Google cloud functions :: cant use 'require' statements - javascript

Issue
When I include any 'require' statements in a google cloud function, I get the warning: "Function is active, but the last deploy failed"
Solution ?
I'm pretty sure I need to include dependencies in the package.json file, but I don't know what dependencies to include, or how to write that.
Background
I've built an android app in Java and I'm trying to integrate stripe payments. Stripe requires me to have a server handle the requests, but I'm trying to use google cloud functions instead (so I don't have to pay / manage a server).
I'm trying to follow this example, but it's not working. The author didn't include the package.json file and I'm not sure what dependencies to put in there. I've never written java script before, my background is in python, c++, java.
I've looked at this tutorial from google as well as the google docs on writing cloud functions. I've also searched S.O. and can't find a solution. The problem may be that I'm not a javascript developer. I'm trying to just plug and play someone else's code to make one specific part of my android (java) app work.
Troubleshooting
To troubleshoot, I used the "helloWorld" example provided by google. The Hello World function works find by itself. If I add any of these three require statements at the top, I get the warning: "Function is active, but the last deploy failed"
Code
-- index.js
var app = require('express')();
var http = require('http').Server(app);
var stripe = require('stripe')(
"your_stripe_key"
);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//initiate a one-off charge for a customer
exports.chargeCustomer = app.get(".../charge/:customerid/:token/:amount", function chargeCustomer (req,res){
stripe.charges.create({
customer: req.params.customerid,
source: req.params.token,
currency: 'usd',
amount:req.params.amount
},function(err, charge) {
if(err) {
return res.send(JSON.stringify(err));
}
res.send(JSON.stringify(charge));
});
});
-- package.json
{
"name": "sample-http",
"version": "0.0.1"
}
Notes
If you know what I'm doing wrong, please remember I've never written javascript. I don't think I'm asking a duplicate question, I've searched, but its possible the answer is in another question and I'm just not understanding it because I've never written javascript.

I wrote the repo that you referenced in your question above. The problem is that you are not formatting your package.json file correctly.
When you deploy your functions, you will need to deploy your index file and a corresponding package.json. You can deploy either through command line, or by simply using the Google in-line editor in the Cloud Functions product.
The package.json file specifies the dependencies that your code needs to run. Basically, your index file needs to know which 3rd party libraries to require for it's functionality. You will notice in my example code below includes a small node for "dependencies", which will tell Google Cloud Functions which packages to install with your code.
The specific index file you reference is creating a charge via Stripe. I use a variation of this code in many production products, and the package.json file looks like this:
{
"name": "createCharge",
"version": "1.0.0",
"description": "create and charge in Stripe",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Your Name",
"license": "ISC",
"dependencies": {
"express": "^4.14.0",
"stripe": "^4.4.0",
"body-parser": "~1.13.3",
"async": "^2.0.1",
"promise": "^7.1.1"
},
"engines": {
"node": "4.1.1"
},
"repository": {
"type": "git",
"url": "<path/to/your/repo.git>"
}
}
Also, just so that you are aware, the "repository" chunk of the above javascript is not required, so if you don't have a hosted repo for this specific function, feel free to delete it.
Hope this helps!

Here is an example with a package.json, it's mentioned in this documentation. I will past an example of its contents:
{
"nyc": {
"exclude": [
"build/src/apis",
"build/test"
]
},
"license": "Apache-2.0",
"dependencies": {
"google-auth-library": "^1.1.0",
"qs": "^6.5.1",
"string-template": "1.0.0",
"uuid": "^3.1.0"
},
...
}
also consider reading npm.js' documentation as package.json is generic and isn't Cloud Function specific.

Related

Parcel localhost server not updating

I am using the parcel (v2.0.1) localhost server with hot module replacement to develop a simple HTML/SASS/JS-based web app. The HMR is working fine most of the time, but from time to time, especially when making significant changes to the code, ALL server updating stops working -- i.e. not only does HMR not work, but I can't even get the server to reflect the changes by reloading the browser page completely or even stopping and restarting the server. To make sure I wasn't just missing something simple I made changes to the code that would DEFINITELY break certain features and restarted the server, but the page still worked as normal.
I have also tried deleting the .parcel-cache and dist folders and re-running parcel and that has not worked either. Restarting my computer has not worked either. The only mention I've seen of this problem is this github discussion.
Has anyone had a similar problem? Thanks!
Here is the package.json file:
{
"name": "",
"version": "1.0.0",
"description": "",
"source": "index.html",
"scripts": {
"start": "parcel index.html",
"build": "parcel build index.html"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#parcel/transformer-sass": "^2.0.1",
"parcel": "^2.0.1"
},
"dependencies": {
"core-js": "^3.19.3",
"fractional": "^1.0.0",
"regenerator-runtime": "^0.13.9"
}
}
I solved this problem with the following code:
"start": "parcel index.html && parcel watch index.html",
Put this in your script tag:
type="module"
Met the same issue: parcel stops working. Especially for me, it happens when I leave a project for day-two and when returned it's broken yet. Even full reinstall (including package.json removing) can't fix the problem. After reinstall, previous broken state is still preserved: it runs recent working code version (I don't understand from where it get the correct code, all data was removed) and doesn't react on any changes except syntax error which cause throwing related errors.

Unable to parse package.json

i'm trying to upload a javascript nodejs project to Heroku.
Localhost works perfectly but when i try to upload it gives me a unable to parse error at :
...
"engines" : { "node" : ">0.11.9" },
...
The Error Message : Invalid numeric literal at line 12, column 0
Full JSON File:
{
"name": "browsergameprojecz",
"version": "1.0.0",
"description": "",
"main": "app.js",
"dependencies": {
"express": "^4.16.3",
"mongojs": "^2.6.0",
"socket.io": "^2.1.1"
},
"engines" : { "node" : ">0.11.9" },
"devDependencies": {},
"scripts": {
"start": "node app.js"
},
"author": "",
"license": "ISC"
}
there are Linters for that, eg. the Package JSON Validator
... which lets one inspect the validity of such JSON files.
besides Node 0.11.9 is roughly 5 years old and tagged as unstable
... consider upgrading, while this is possible in combination with the rest.
there might be Windows line-ending in that file ...as it often is the case, when "everything looks fine", but still not works are excepted. dos2unix can be used to fix them.
https://techblog.dorogin.com/writing-cross-platform-npm-scripts-on-windows-79c510339ea6 hints for, that when files have a UTF-8 BOM 0x EF BB BF at the beginning, this also makes it un-parse-able. unless checking this with a hex-editor, one can not know. simply creating a new package.json with UTF-8 endoding and UNIX \n line-endings should resolve the issue.
This is from the official npm docs. It looks like you need a range for a version not just a lower limit. Or an approximate version. However from my experience with Heroku I have never needed this it seems heroku will probably use a node version much higher. Also if you need a specific version there is such a thing called engineStrict which you can have a look at in the official npm docs.
When the data is upload to the client from the server side in JSON format, some special characters can not be displayed directly when the JS is displayed on the HTML page. As the background is passed through the <b>msg</b>, it is displayed in the HTML page msg by JS, and it is not msg. This is due to the content between < and > as HTML. Tagging, and start with HTML as entity, so the display is not normal.
The solution is simple, and can be rendered before JS is rendered to HTML pages.

Create a CLI interface with Node own commands not working

Currently I am following the following tutorial
The tutorial basically is meant to create a node cli that allow me to CRUD contacts directly on the cli.
I want to do it without mongoose, since what I need is to perform cli commands that does requests to the server to extract data, but that is other history, just to explain that I do not use mongoose here. The first step worked well, basically if I do: node contact.js -- help, it calls the help command on my contact.js file.
The issue comes when I want to take out the node command, I basically want to call it like that, contact --help. That is not working, I used yarn link and followed the instructions on the tutorial, so what is wrong? Any help?
Here is what I did so far:
package.json
{
"name": "contacto",
"version": "1.0.0",
"main": "index.js",
"preferGlobal": true,
"bin": "./contact.js",
"license": "MIT",
"dependencies": {
"commander": "^2.15.1",
"inquirer": "^5.2.0",
"mongoose": "^5.0.12"
}
}
contact.js
#!/usr/bin/env node
/**
* We build a cli that is responsable to interact with the IPMA service, to filter any option, for options we mean: Temperature
* eartquake activity and another possible options, the next argument will be the zone(city),
*/
const program = require('commander');
program
.version('0.0.1')
.description('Contact management system');
program
.command('addContact <firstame> <lastname> <phone> <email>')
.alias('a')
.description('Add a contact')
.action((firstname, lastname, phone, email) => {
console.log(firstname,lastname,phone,email);
});
program.parse(process.argv);
The executable is created based on the package name, not on the name of the folder or the file.
As you have defined in the package.json, the name of the module is contacto (mind the 'o' at the end). This is the global executable name after you run the command yarn link.
The right way to execute the CLI in this case is: contacto --help

Raven doesn't use source maps in Sentry for TS/JS code

I already used Sentry in a C# project and was very pleased about it. So I also want to use it in a new NodeJS project with TypeScript. Sadly, the required sourcemaps doesn't work fine here. I first tried it in a plain TS project without success. Even in a plain raw JS project it doesn't do any source code mapping.
For the test project, I exactly followed the documentation on node/sourcemaps:
https://docs.sentry.io/clients/node/config/
https://docs.sentry.io/clients/node/sourcemaps/#webpack
https://docs.sentry.io/clients/node/typescript/
The result is always the same, Sentry shows me the ugly code without using sourcemaps:
It seems that Sentry doesn't use the sourcemaps for unknown reasons cause the corresponding Release contains the required sourcemap:
I spend a lot of hours on this. Tried several things, including different paths/file names for the files pushed to sentry. I also used the Sentry cli tool directly, to make sure, that there is no issue with the webpack plugin. Nothing works, Sentry always shows me the raw source code and ignores the sourcemap.
The following files are from my second nodejs program using plain raw JavaScript. It's as minified as possible to work. I don't know whats wrong here cause I did exactly what the documentation requires.
What is the problem?
Sourcemaps were generated and uploaded. First I thought that the file names/paths doesn't match. This older question shows a similar issue, where the paths doesn't match since they were not relative using ~/ but in SentryPlugin this is the default prefix. On the other side, dataCallback make sure that all paths are relative to the project root, instead of having absolut paths like /home/user/project/dist/app.js which would be the default behavior. I did a console.log there to see that they're correctly relative.
Simple NodeJS test project using plain raw JavaScript
src/app.js (Main programm)
var Raven = require('raven')
const path = require('path')
let options = {
release: process.env.RELEASE,
dataCallback: function (data) {
var stacktrace = data.exception && data.exception[0].stacktrace;
if (stacktrace && stacktrace.frames) {
stacktrace.frames.forEach(function (frame) {
if (frame.filename.startsWith('/')) {
frame.filename = 'app:///' + path.basename(frame.filename);
}
});
}
return data;
}
}
Raven.config('http://<DnKey>#<SentryHost>:9000/3', options).install();
//Raven.captureException(new Error('abc'))
throw new Error('Hello123')
webpack.config.js
In this file, I changed the entry path from src/app.js to ./src/app.js. The Sentry docs use ./src/app.js but this result in an error that the path cannot be resolved. It appears to be an mistake of the docs.
const path = require('path')
const fs = require('fs')
const SentryPlugin = require('#sentry/webpack-plugin')
module.exports = {
target: 'node',
devtool: 'source-map',
entry: {
"app": './src/app.js'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
plugins: [
new SentryPlugin({
release: process.env.RELEASE,
configFile: 'sentry.properties',
include: './dist',
ignore: ['node_modules', 'webpack.config.js'],
})
]
};
sentry.properties
I added the configFile attribute since SentryPlugin uses internally the CLI of Sentry. The CLI needs to know some information like url or auth-token from Sentry. This could be passed as environment variables, but I like the approach of using a config file, which is completely valid according to the docs. Token has project.write permission as required.
defaults.url=http://SentryHost:9000
defaults.org=sentry
defaults.project=js-test
auth.token=xxx
package.json
{
"name": "sentry-js-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "rm -rf dist/* && webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#sentry/cli": "^1.30.2",
"#sentry/webpack-plugin": "^1.3.3",
"raven": "^2.4.2",
"webpack": "^4.0.1"
},
"devDependencies": {
"webpack-cli": "^2.0.10"
}
}
Start the test programm
export RELEASE=3.0.20 && npm run build && node dist/app.js
This use webpack to minify src/app.js and place the minified version in dist/app.js. Furthermore, it creates a sourcemap called dist/app.js.map.
On every run, I changed RELEASE (e.g. increment to 3.0.21). That's important since Sentry assumes, that releases and source files (also sourcemaps) are a 1:1 relation. So if we upload our files to release with version 3.0.20 this is done on the first time. On the second time, the files keeps unchanged cause the cli sees that they're already existing. Using a new version make sure that our latest changed files are always uploaded and we don't mess with old ones from playing around.
I spend a lot of hours on this issue and have no Idea what I'm doing wrong. Summarized, I did every step from the tutorials of the documentation, with some small fixes on obvious errors.
Information about the environment
I'm using self hosted Sentry 8.22 in docker containers on Arch Linux. NodeJS is used in Version 9.7.1.
After months struggling with that we finally found the issue.
You can see that the artifacts are here with the sourcemaps, that you correctly tag the versions and everything seems fine?
Running Sentry on your own I bet? We are too.
Well that's the issue.
Sentry is divided into different services and in order to have them sharing the data (sourcemaps...) you need to share a volume between them. Please read that post where it's correctly explained.
Also, if you prefer, you can host them on S3 and Sentry can work with that too!

Javascript code completion for arango and module handling

Introduction
I've been using Eclipse for Java(!) development for more than a decade. Due to high demand I'm jumping in the deep end with javascript and arangodb. Task is to develop several microservices running within arangodb.
I'm free to use the IDE/Editor of my choice. Only remaining competitors are MS VS Code and IntelliJ. VS Code beeing my favorite as of writing.
Project setup
According to arangos documentation I've composed a project with:
mainfest.json (content skipped to improve readability)
package.json
{
"name": "abc",
"version": "0.0.2",
"description": "foxxy service",
"comment" : "This file contains the NPM package definition",
"main": "main.js",
"directories": {
"test": "test"
},
"dependencies": {
"crypto-js": "^3.1.9-1",
"jsonq": "^1.1.0",
"xml2js": "^0.4.19",
"xmldom": "^0.1.27",
"xpath.js": "^1.0.7"
},
"devDependencies": {
"chai": "^4.1.1",
"mocha": "^3.5.0"
},
"scripts": {
"test": "node node_modules/mocha/bin/mocha"
}
}
jsconfig.json
{
"compilerOptions": {
"target": "ES6",
"checkJs": true
},
"include": [
"scripts/**/*",
"lib/**/*",
"models/**/*",
"node_modules/#arangodb/**/*",
"node_modules/jsonq/**/*",
"node_modules/xml2js/**/*",
"/*"
]
}
Current state
VS Studio Code offers code completion for:
- standard Javascript (ES6) expressions
- resolves actual files behind require expressions ( e.g.: require('lodash') is resolved to the actual filesystem path
C:/Users/notte/AppData/Local/Microsoft/TypeScript/2.5/node_modules/#types/lodash/index' which proves (for me) that npm module resolution and code completion are working
Question
Arango does not offer modules via npmjs or other public repositories. I therefore copied the files (#arangodb) from an local arangodb installation to the projects "node_modules" folder.
Altough VS Code is informed about the #arango modules and submodules it does not come up with a useful code completion. What should I do or try to do?
What would be a pragmatic, sustainable solution for handling modules like those from arango? (it is not present in npmjs, has no package.json and hence no versioning)
Thank you.
We Currently collecting user efforts to create Syntax hilighting via https://github.com/arangodb/arangodb/issues/1755 - Please share your thoughts if you have something to add.

Categories

Resources