How to use module in parse-server cloud code? - parse-server

I have the following code which Parse has posted before on their blogs, such as this one.
var _ = require("underscore");
Parse.Cloud.beforeSave("Post", function(request, response) {
var post = request.object;
var toLowerCase = function(w) { return w.toLowerCase(); };
var words = post.get("text").split(/b/);
words = _.map(words, toLowerCase);
var stopWords = ["the", "in", "and"]
words = _.filter(words, function(w) { return w.match(/^w+$/) && ! _.contains(stopWords, w); });
var hashtags = post.get("text").match(/#.+?b/g);
hashtags = _.map(hashtags, toLowerCase);
post.set("words", words);
post.set("hashtags", hashtags);
response.success();
});
The issue is that I cannot use npm start to start my server since it crashes on the line var _ = require("underscore"); . The error is
Error: Cannot find module 'underscore'.
How could I fix this in the context of parse-server's cloud code?

Simply go to package.json in your parse-server and add underscore.js as a dependency, as seen below.
"dependencies": {
"express": "~4.11.x",
"kerberos": "~0.0.x",
"parse-server": "^2.2.15",
"parse": "~1.8.0",
"nconf": "0.8.4",
"underscore": "1.8.3"
}
Then, if running the server locally, use:
npm install
and then
npm start
and the cloud code will now run fine.

Related

What are cloudflare KV preview_ids and how to get one?

I have a following wrangler.toml. When I would like to use dev or preview (e.g. npx wrangler dev or npx wrangler preview) wrangler asks to add a preview_id to the KV namespaces. Is this an identifier to an existing KV namespace?
I see there is a ticket in Cloudflare Workers GH at https://github.com/cloudflare/wrangler/issues/1458 that tells this ought to be clarified but the ticket is closed with adding an error message
In order to preview a worker with KV namespaces, you must designate a preview_id in your configuration file for each KV namespace you'd like to preview."
which is the reason I'm here. :)
As for larger context I would be really glad if someone could clarify: I see that if I give a value of an existing namespace, I can preview and I see a KV namespace of type __some-worker-dev-1234-workers_sites_assets_preview is generated in Cloudflare. This has a different identifier than the KV namespace pointed by the identifier used in the preview_id and the KV namespace pointed by the identifier I used in preview_id is empty. Why does giving an identifier of an existing KV namespace remove the error message, deploys the assets and allow for previwing but the actual KV namespace is empty and a new one is created?
How do does kv-asset-handler know to look into this generated namespace to retrieve the assets?
I'm currently testing with the default generated Cloudare Worker to my site and I wonder if I have misunderstood something or if there is some mechanics that bundles during preview/publish the site namespace to the scipt.
If there is some random mechanics with automatic mapping, can this be then so that every developer can have their own private preview KV namespace?
type = "javascript"
name = "some-worker-dev-1234"
account_id = "<id>"
workers_dev = true
kv_namespaces = [
{ binding = "site_data", id = "<test-site-id>" }
]
[site]
# The location for the site.
bucket = "./dist"
# The entry directory for the package.json that contains
# main field for the file name of the compiled worker file in "main" field.
entry-point = ""
[env.production]
name = "some-worker-1234"
zone_id = "<zone-id>"
routes = [
"http://<site>/*",
"https://www.<site>/*"
]
# kv_namespaces = [
# { binding = "site_data", id = "<production-site-id>" }
# ]
import { getAssetFromKV, mapRequestToAsset } from '#cloudflare/kv-asset-handler'
/**
* The DEBUG flag will do two things that help during development:
* 1. we will skip caching on the edge, which makes it easier to
* debug.
* 2. we will return an error message on exception in your Response rather
* than the default 404.html page.
*/
const DEBUG = false
addEventListener('fetch', event => {
try {
event.respondWith(handleEvent(event))
} catch (e) {
if (DEBUG) {
return event.respondWith(
new Response(e.message || e.toString(), {
status: 500,
}),
)
}
event.respondWith(new Response('Internal Error', { status: 500 }))
}
})
async function handleEvent(event) {
const url = new URL(event.request.url)
let options = {}
/**
* You can add custom logic to how we fetch your assets
* by configuring the function `mapRequestToAsset`
*/
// options.mapRequestToAsset = handlePrefix(/^\/docs/)
try {
if (DEBUG) {
// customize caching
options.cacheControl = {
bypassCache: true,
}
}
const page = await getAssetFromKV(event, options)
// allow headers to be altered
const response = new Response(page.body, page)
response.headers.set('X-XSS-Protection', '1; mode=block')
response.headers.set('X-Content-Type-Options', 'nosniff')
response.headers.set('X-Frame-Options', 'DENY')
response.headers.set('Referrer-Policy', 'unsafe-url')
response.headers.set('Feature-Policy', 'none')
return response
} catch (e) {
// if an error is thrown try to serve the asset at 404.html
if (!DEBUG) {
try {
let notFoundResponse = await getAssetFromKV(event, {
mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req),
})
return new Response(notFoundResponse.body, { ...notFoundResponse, status: 404 })
} catch (e) {}
}
return new Response(e.message || e.toString(), { status: 500 })
}
}
/**
* Here's one example of how to modify a request to
* remove a specific prefix, in this case `/docs` from
* the url. This can be useful if you are deploying to a
* route on a zone, or if you only want your static content
* to exist at a specific path.
*/
function handlePrefix(prefix) {
return request => {
// compute the default (e.g. / -> index.html)
let defaultAssetKey = mapRequestToAsset(request)
let url = new URL(defaultAssetKey.url)
// strip the prefix from the path for lookup
url.pathname = url.pathname.replace(prefix, '/')
// inherit all other props from the default request
return new Request(url.toString(), defaultAssetKey)
}
}
In case the format is not obvious (it wasn't to me) here is a sample config block from the docs with the preview_id specified for a couple of KV Namespaces:
kv_namespaces = [
{ binding = "FOO", id = "0f2ac74b498b48028cb68387c421e279", preview_id = "6a1ddb03f3ec250963f0a1e46820076f" },
{ binding = "BAR", id = "068c101e168d03c65bddf4ba75150fb0", preview_id = "fb69528dbc7336525313f2e8c3b17db0" }
]
You can generate a new namespace ID in the Workers KV section of the dashboard or with the Wrangler CLI:
wrangler kv:namespace create "SOME_NAMESPACE" --preview
This answer applies to versions of Wrangler >= 1.10.0
wrangler asks to add a preview_id to the KV namespaces. Is this an identifier to an existing KV namespace?
Yes! The reason there is a different identifier for preview namespaces is so that when developing with wrangler dev or wrangler preview you don't accidentally write changes to your existing production data with possibly buggy or incompatible code. You can add a --preview flag to most wrangler kv commands to interact with your preview namespaces.
For your situation here there are actually a few things going on.
You are using Workers Sites
You have a KV namespace defined in wrangler.toml
Workers Sites will automatically configure a production namespace for each environment you run wrangler publish on, and a preview namespace for each environment you run wrangler dev or wrangler preview on. If all you need is Workers Sites, then there is no need at all to specify a kv-namepsaces table in your manifest. That table is for additional KV namespaces that you may want to read data from or write data to. If that is what you need, you'll need to configure your own namespace and add id to wrangler.toml if you want to use wrangler publish, and preview_id (which should be different) if you want to use wrangler dev or wrangler preview.

Truffle test fails with Error: Could not find artifacts

I learn the demo: Code is come from: https://truffleframework.com/tutorials/pet-shop, when I test:
$ truffle.cmd test
Using network 'development'.
Compiling .\test\TestAdoption.sol...
TestAdoption
1) "before all" hook: prepare suite
0 passing (30s)
1 failing
1) TestAdoption
"before all" hook: prepare suite:
Error: Could not find artifacts for /E/blockchain/pet-
shop/contracts/Adoption.sol from any sources
at Resolver.require (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-resolver\index.js:37:1)
at TestResolver.require (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\testresolver.js:17:1)
at TestResolver.require (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\testresolver.js:17:1)
at dependency_paths.forEach.dependency_path (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\soliditytest.js:203:1)
at Array.forEach (<anonymous>)
at deployer.deploy.then (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\soliditytest.js:202:1)
at D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-deployer\src\deferredchain.js:20:1
at process._tickCallback (internal/process/next_tick.js:68:7)
I updated my nodejs lastest, and installed window-build-tools,it does not work.
TestAdoption.sol:
pragma solidity ^0.5.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/Adoption.sol";
contract TestAdoption {
Adoption adoption = Adoption(DeployedAddresses.Adoption());
function testUserCanAdoptPet() public {
uint returnedId = adoption.adopt(expectedPetId);
Assert.equal(returnedId, expectedPetId);
}
uint expectedPetId = 8;
address expectedAdopter = address(this);
function testGetAdopterAddressByPetId() public {
address adopter = adoption.adopters(expectedPetId);
Assert.equal(adopter, expectedAdopter, "Owner of the expected pet should be this contract");
}
function testGetAdopterAddressByPetIdInArray() public {
address[16] memory adopters = adoption.getAdopters();
Assert.equal(adopters[expectedPetId], expectedAdopter, "Owner of the expected pet should be this contract");
}
}
2_deploy_contracts.sol:
var Adoption = artifacts.require("Adoption");
module.exports = function(deployer) {
deployer.deploy(Adoption);
};
And import "truffle/Assert.sol"; vscode say: Source "truffle/Assert.sol" not found: File import callback not supported.My friend's version is 0.4.14 and work well, may be a version problem?
Here is project dir(just a demo from https://truffleframework.com/tutorials/pet-shop):
This error DOESN'T happen (currently) in the version v5.1.10 of truffle.
My full error was:
TypeError: Error parsing C:/Users/PATH/yourSmartContract.sol: Cannot destructure property 'body' of 'undefined' as it is undefined.
My solution is to downgrade the version like so:
$ npm uninstall -g truffle
$ npm install -g truffle#v5.1.10
(Developing in BC is hard because of version control and managment. Keep the good the work.)
The problem is the name of the artifact is defined according to the contract's name. This is your contract:
contract TestAdoption {
}
So;
2_deploy_contracts.sol:
// not artifactsrequire(Adoption)
var Adoption = artifacts.require("TestAdoption");
module.exports = function(deployer) {
deployer.deploy(Adoption);
};
Try these files:
1_initial_migration.js:
const Migrations = artifacts.require("Migrations");
module.exports = function(deployer) {
deployer.deploy(Migrations);
};
2_deploy_contracts.js:
const YourContractName = artifacts.require("YourContractName");
module.exports = function(deployer) {
deployer.deploy(YourContractName);
};
Tips:
Do not change the name of the files (1_initial_migration.js and 2_deploy_contracts.js);
Use the exactly name of your contract in the "2_deploy_contracts" file (if it is called BatatinhaFrita123, you need to specify BatatinhaFrita123 inside the artifacts.require()).

Error parsing triggers: Cannot find module 'firebase/firestore'

I am trying to run a very basic code on google api using firebase.
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
//const {Card, Suggestion} = require('dialogflow-fulfillment');
var admin = require('firebase-admin');
require("firebase/firestore");
admin.initializeApp(functions.config().firebase);
//var firestore = admin.firestore();
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
//firestore arguments defined
/* var addRef = firestore.collection('Admissions');
var feeRef = firestore.collection('Fees');
*/
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
console.log("request.body.queryResult.parameters: ", request.body.queryResult.parameters);
// Run the proper function handler based on the matched Dialogflow intent name
var intentMap = new Map();
});
It gives me a error that says
'Error parsing triggers: Cannot find module 'firebase/firestore'.Try running "npm install" in your functions directory before deploying.
When I run npm install inside the funtions directory, I get:
audited 9161 packages in 25.878s found 292 vulnerabilities (21 low,
207 moderate, 64 high) run npm audit fix to fix them, or npm
audit for details
Its been a week, I am stuck with these errors, these errors keep fluctuating based on the solution i find. But i am not able to overcome this error. Can you please check if there is something wrong I am doing, or anything else I need to try?
Just delete the node_modules folder and run npm install again. I was also stuck on this for a week. It is a corrupt file issue.

Google Cloud Storage - Error during upload: gcs-resumable-upload.json renaming operation not permitted

I'm simply trying to follow this tutorial on how to upload files to gcs with Node and Express. But the following error keep causing my app to crash. Usually, I am able to upload one file without a problem in the first run. But I will get this error after running a few request, even with different file. When I try to upload, say 5, files at a time, this error cause my app to crash even in the first run. I see the process is trying to rename a file in the .config folder. Is it a normal behavior? If so, is there a work-around?
Window: v10.0.10586
Node: v4.3.1
Express: v4.13.1
Error: EPERM: operation not permitted, rename 'C:\Users\James Wang.config\configstore\gcs-resumable-upload.json.2873606827' -> 'C:\Users\James Wang.config\configstore\gcs-resumable-upload.json'
at Error (native)
at Object.fs.renameSync (fs.js:681:18)
at Function.writeFileSync as sync
at Object.create.all.set (C:\Users\James Wang\gi-cms-backend\node_modules\configstore\index.js:62:21)
at Object.Configstore.set (C:\Users\James Wang\gi-cms-backend\node_modules\configstore\index.js:93:11)
at Upload.set (C:\Users\James Wang\gi-cms-backend\node_modules\gcs-resumable-upload\index.js:264:20)
at C:\Users\James Wang\gi-cms-backend\node_modules\gcs-resumable-upload\index.js:60:14
at C:\Users\James Wang\gi-cms-backend\node_modules\gcs-resumable-upload\index.js:103:5
at Request._callback (C:\Users\James Wang\gi-cms-backend\node_modules\gcs-resumable-upload\index.js:230:7)
at Request.self.callback (C:\Users\James Wang\gi-cms-backend\node_modules\request\request.js:199:22)
at emitTwo (events.js:87:13)
at Request.emit (events.js:172:7)
at Request. (C:\Users\James Wang\gi-cms-backend\node_modules\request\request.js:1036:10)
at emitOne (events.js:82:20)
at Request.emit (events.js:169:7)
at IncomingMessage. (C:\Users\James Wang\gi-cms-backend\node_modules\request\request.js:963:12)
[nodemon] app crashed - waiting for file changes before starting...
UPDATE:
After setting {resumable: false} as suggested by #stephenplusplus in this post, I am no longer getting the "EPERM: operation not permitted" error.But, I start running into the { [ERROR:ETIMEDOUT] code: 'ETIMEDOUT', connection: false } error while trying to upload multiple files at a time with the largest file greater than 1.5mb. Other files get uploaded successfully.
For more information, I am able to upload files one by one when the files are no greater than ~2.5mb. If I try to upload 3 files at a time, I can only do so with files no greater than ~1.5mb.
Is the "Operation not permitted" issue as specified in the question a window specific thing, and does the timeout issue happen only after i set resumable = false?
I'm using express and multer with node.
This is the code I'm using now:
// Express middleware that will handle an array of files. req.files is an array of files received from
// filemulter.fields([{field: name, maxCount}]) function. This function should handle
// the upload process of files asychronously
function sendFilesToGCS(req, res, next) {
if(!req.files) { return next(); }
function stream(file, key, folder) {
var gcsName = Date.now() + file.originalname;
var gcsFile = bucket.file(gcsName);
var writeStream = gcsFile.createWriteStream({ resumable: false });
console.log(key);
console.log('Start uploading: ' + file.originalname);
writeStream.on('error', function(err) {
console.log(err);
res.status(501).send(err);
});
writeStream.on('finish', function() {
folder.incrementFinishCounter();
req.files[key][0].cloudStorageObject = gcsName;
req.files[key][0].cloudStoragePublicUrl = getPublicUrl(gcsName);
console.log('Finish Uploading: ' + req.files[key][0].cloudStoragePublicUrl);
folder.beginUploadNext();
});
writeStream.end(file.buffer);
};
var Folder = function(files) {
var self = this;
self.files = files;
self.reqFilesKeys = Object.keys(files); // reqFilesKeys is an array of keys parsed from req.files
self.nextInQuene = 0; // Keep track of the next file to be uploaded, must be less than reqFilesKeys.length
self.finishCounter = 0; // Keep track of how many files have been uploaded, must be less than reqFilesKeys.length
console.log(this.reqFilesKeys.length + ' files to upload');
};
// This function is used to initiate the upload process.
// It's also called in the on-finish listener of a file's write-stream,
// which will start uploading the next file in quene
Folder.prototype.beginUploadNext = function() {
// If there's still file left to upload,
if(this.finishCounter < this.reqFilesKeys.length) {
// and if there's still file left in quene
if(this.nextInQuene < this.reqFilesKeys.length) {
// upload the file
var fileToUpload = this.files[this.reqFilesKeys[this.nextInQuene]][0];
stream(fileToUpload, this.reqFilesKeys[this.nextInQuene], this);
// Increment the nextInQuene counter, and get the next one ready
this.nextInQuene++;
}
} else {
console.log('Finish all upload!!!!!!!!!!!!!!!!!!!!!!');
next();
}
};
Folder.prototype.incrementFinishCounter = function() {
this.finishCounter++;
console.log('Finished' + this.finishCounter + ' files');
};
var folder = new Folder(req.files);
// Begin upload with 3 streams
/*for(var i=0; i<3; i++) {
folder.beginUploadNext();
}*/
//Upload file one by one
folder.beginUploadNext();
}
I had the same issue with bower .. Run the following command: bower cache clean --allow-root
if this does not solve the problem, try after disabling anti virus.

Error while installing the corona sdk plugin

This is what i a getting on my Corona Simulator Output when i try to install the 'playhaven' plugin. I don't know how to get rid of this.
Build: 2013.1202 Runtime error ?:0: attempt to call field 'request' (a nil value) stack traceback:
[C]: in function 'request'
?: in function 'downloadManifest'
?: in function 'downloadQueuedManifests'
?: in function <?:632>
?: in main chunkRuntime error
stack traceback:
[C]: in function 'request'
?: in function 'downloadManifest'
?: in function 'downloadQueuedManifests'
?: in function <?:632>
?: in main chunk
In case you wanna take a look at my build.settings file because after i integrated the plugins into the build.settings file. I recieved the error i showed above.
settings =
{
orientation =
{
default = "portrait",
supported = { "portrait" },
},
androidPermissions =
{
"android.permission.ACCESS_COARSE_LOCATION",
"android.permission.ACCESS_FINE_LOCATION",
"android.permission.INTERNET",
"android.permission.READ_PHONE_STATE",
"android.permission.ACCESS_NETWORK_STATE",
},
plugins =
{
-- key is the name passed to Lua's 'require()'
["plugin.playhaven"] =
{
-- required
publisherId = "com.playhaven",
},
},
iphone =
{
plist =
{
UIPrerenderedIcon = true,
UIApplicationExitsOnSuspend = false,
CFBundleIconFile = "Icon.png",
CFBundleIconFiles = {
"Icon.png",
"Icon#2x.png",
},
},
},
}
Playhaven is only available to Pro and Enterprise subscribers. See:
http://docs.coronalabs.com/daily/plugin/playhaven/
Are you a Pro or a Starter?
Since you gave so few information on your system and environment I can only guess. It seems that the installer tried to download something (or connect via some protocol) and failed. Did you check your firewall/proxy settings? Maybe connections are automatically refused and you are not aware of it.