I recently migrated parseserver to heroku, and everything seems to work perfectly except in my Cloud Code any Parse.Query does not seem to ever respond.
I can run custom cloud code, however anytime I need to run a Parse.Query the request times out.
here is my code:
Parse.Cloud.define("get_remaining_minutes", function(request, response) {
var config_name = "RWMTrialMinutes";
var minutesForPeriod = 120;
var isTrial = true;
var periodStartDate = new Date("01/01/2015");
var minutesUsed = 0;
console.log("userId=" + request.params.userId);
var userQuery = new Parse.Query(Parse.User);
userQuery.get({ useMasterKey: true }).then(request.params.userId, {
success: function(user) {
console.log("success");
response.success(100);
},
error: function(object, error) {
console.log("failed");
response.error(error);
}
});
});
I then call:
curl -X POST -H "X-Parse-Application-Id: xxx" https://xxx.herokuapp.com/parse/functions/get_remaining_minutes?userId=dMbBrRGD1y
and get a timeout
2016-10-13T17:21:21.858269+00:00 heroku[router]: at=info method=POST path="/classes/_User" host=xxx.herokuapp.com request_id=xxx fwd="xxx" dyno=web.1 connect=0ms service=7ms status=404 bytes=225
2016-10-13T17:21:21.788404+00:00 app[web.1]: userId=dMbBrRGD1y
2016-10-13T17:21:51.759088+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/parse/functions/get_remaining_minutes?userId=dMbBrRGD1y" host=xxxx.herokuapp.com request_id=xxx fwd="xxx" dyno=web.1 connect=1ms service=30000ms status=503 bytes=0
I've tried many different ways to query - tried .first, .get, .find, all seem to do the same thing - timeout. If i skip the .get call, the function works fine and I can response.success correctly. However I obviously need to make the query for my code to work.
I feel like i'm missing something basic, like a require or maybe a path is not set up correctly.
I will also mention I am running parse server and dashboard on the same Heroku application if you think that makes a difference as to why the cloud code is failing.
Any ideas?
Edit: adding my index.js code for starting parse-server and dashboard
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var ParseDashboard = require('parse-dashboard');
var path = require('path');
var allowInsecureHTTP = true;
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'xxx',
masterKey: process.env.MASTER_KEY || '',
serverURL: process.env.SERVER_URL || 'xxx.herokuapp.com/parse',
restAPIKey: 'xxx',
push:{
ios:{
pfx: 'Push.p12',
bundleId: 'xxx',
production: true
}
}
}, allowInsecureHTTP);
var dashboard = new ParseDashboard({
users: [{
user: 'admin',
pass: 'xxx'
}],
apps: [
{
serverURL: process.env.SERVER_URL + process.env.PARSE_MOUNT || 'https://xxx.herokuapp.com/',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || '',
appName: process.env.APP_NAME || 'StoryTime',
iconName: 'Icon-60.png'
}
],
"iconsFolder": "icons"
}, allowInsecureHTTP);
var app = express();
app.use('/public', express.static(path.join(__dirname, '/public')));
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);
//start the dashboard
app.use('/dashboard', dashboard);
app.get('/', function(req, res) {
res.status(200).send('I dream of being a website. Please star the parse- server repo on GitHub!');
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
Turns out there were two problems - first the server was configured incorrectly. the SERVER_URL did not have /parse on it - and because the PARSE_MOUNT property was being used to route in express, I missed it. Second the syntax for useMasterKey needs to be like this for .get() - I had copied the code from somewhere online and it was not correct.
userQuery.get(request.params.userId, { useMasterKey:true, success: function(user)....
Related
Before Oct 2022, Infura.io allow users to post using its gateway as follows: No auth is required. My original code is as follows in ipfs.js file.
const IPFS = require('ipfs-api');
const ipfs = new IPFS({host: 'ipfs.infura.io', port: 5001, protocol: 'https'});
export default ipfs;
When auth is needed I included the following:
const projectId ='ZZZZZZZZZZZZZZz';
const projectSecret='ZXXXZZXXXXXXXXXX';
const auth = 'Bearer ' + (projectId + ':' +projectSecret);
const ipfs = new IPFS({
host: 'ipfs.infura.io',
//host: 'nftpatent.infura-ipfs.io/',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
}
});
The issue is that i am unable to upload and post/pin to IPFS. My first thought is that I use the wrong host which should be the dedicated 'nftpatent.infura-ipfs.io' as this requires the auth but from what I have read research it seems everything stays the same and we need to provide auth only.
In my App.js, I have this to do the heavy lifting
// save document to IPFS,return its hash#, and set hash# to state
// https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/FILES.md#add
//setState by setting ipfsImageHash to ipfsImageHash[0].hash
if (this.state.myToken.imageBuffer && this.state.myToken.imageBuffer.length > 0) {
await ipfs.add(this.state.myToken.imageBuffer, (err, ipfsHash) => {
console.log('IPFS hash: ' + ipfsHash + ', error: ' + err);
let myMetadata = JSON.parse(JSON.stringify(this.state.myToken.metadataBuffer));
myMetadata.image = this.state.web3ctx.ipfsGateway + ipfsHash[0].hash;
this.setState({
myToken: {
...this.state.myToken,
ipfsImageHash: ipfsHash[0].hash,
ipfsImageUrl: myMetadata.image,
metadataBuffer: myMetadata,
imageBuffer: ''
},
selectedTab: 'Metadata'
});
})
} else if (this.state.myToken.metadataBuffer && this.state.myToken.metadataBuffer.toString().length > 0) {
await ipfs.add(Buffer.from(JSON.stringify(this.state.myToken.metadataBuffer)), (err, ipfsHash) => {
console.log('IPFS hash: ' + ipfsHash + ', error: ' + err);
this.setState({
myToken: {
...this.state.myToken,
ipfsMetadataHash: ipfsHash[0].hash,
ipfsMetadataUrl: this.state.web3ctx.ipfsGateway + ipfsHash[0].hash
},
selectedTab: 'Metadata'
});
})
} else {
console.log('file could not be found: '
+ JSON.stringify(this.state.myToken.metadataBuffer, null, 2));
return 1;
}
};
`
And the error is
TypeError: Cannot read properties of undefined (reading '0')
Duplex.
src/App.js:287
myMetadata.image = this.state.web3ctx.ipfsGateway + ipfsHash[0].hash;
enter image description here
Please help as I can't seem to figure out the issues. ``
I tried working the auth and checking whether the host is correctly called. I believe the issue is with "auth" and not with scripts as they were working previously. Thanks in advance. `
I am building my first Shopify public app and used their Next.js and React example to get started. I needed to create an API and couldn't route it with Next.js so I added Koa and Koa-Routes to map it.
It works well locally and I'm able to post and get information from my database using the API. When I deploy it on Heroku, these Koa routes do not work anymore and return 404 errors.
server.js (only the relevant bits)
const Koa = require('koa');
const Router = require('koa-router');
var bodyParser = require('koa-bodyparser');
const next = require('next');
const routes = require('./routes')
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
app.prepare().then(() => {
const server = new Koa();
const router = new Router();
server.use(bodyParser());
server.use(session(server));
server.keys = [SHOPIFY_API_SECRET_KEY];
require('./routes/api')(router);
...
./routes/api
const SettingsControllers = require('../controller/settings');
module.exports = function(router){
router.get('/api/settings/:shop', SettingsControllers.find);
router.put('/api/settings', SettingsControllers.save);
return router
}
Here is the message I get on API calls
heroku[router]: at=info method=GET path="/api/settings/13msdev.myshopify.com" host=app.website.com request_id=12345 fwd="12.12.12.12.12" dyno=web.1 connect=0ms service=3ms status=404 bytes=2020 protocol=https
I can deploy my app locally, but not on heroku. I'm using nodemailer and trying to send mail to myself from my website. This is the route:
app.post('/contact', function (req, res) {
let mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport({
servic: 'gmail',
auth: {
user: 'randomemail',
pass: 'password'
}
});
mailOpts = {
from: req.body.name + ' <' + req.body.email + '>',
to: 'randomemail',
subject: 'New message from contact form at your portfolio page',
text: `${req.body.name} (${req.body.email}) says: \n \n ${req.body.message}`
};
smtpTrans.sendMail(mailOpts, function (error, response) {
if (error) {
res.render('contact-failure');
}
else {
res.send(response);
}
});
});```
And this is the error I get when I try to send myself mail from heroku.
2018-05-29T06:31:32.280501+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="/contact" host=desolate-journey-40239.herokuapp.com request_id=4c462f91-9f47-4566-943a-2c5e24d795ac fwd="75.74.137.60" dyno=web.1 connect=0ms service=89ms status=503 bytes=0 protocol=https
NOTE: Some things I've tried going here: https://accounts.google.com/b/0/DisplayUnlockCaptcha and unlocking my account to no avail.
Any response is appreciated. Thanks in advance.
I noticed the typo on 'service' and that seems to have fixed my error.
I have a parse server running in clustering, everything works perfectly but in the last days I have had to add live queries, just activate it in the configuration doesn't work very well, because the event "create" is triggered only few times (while not in clustering it doesn't miss one).
From parse documentation it's suggested to use redis, and here is my problem: I don't understand how the parse's db is passed to redis' db to work properly.
Could please someone just put me on right path?
When you configure your ParseServer, there's an option to include the URL for the Redis server and set the class names for which you want to enable Live Queries:
liveQuery: {
classNames: ['_User', 'Map'],
redisURL: 'redis://localhost:6379'
}
Full setup:
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://IP:PORT/PATH',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'AppID',
masterKey: process.env.MASTER_KEY || 'MasterKey', //Add your master key here. Keep it secret!
//javascriptKey: process.env.JAVASCRIPT_KEY || '',
serverURL: process.env.SERVER_URL || 'http://IP:PORT/parse', // Don't forget to change to https if needed
liveQuery: {
classNames: ['ExampleClass'], // Add Class names here
redisURL: 'redis://REDIS_IP:REDIS_PORT'
},
});
var app = express();
var port = process.env.PORT || 1111;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('App on port ' + port + '.');
});
// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer, {
redisURL: 'redis://REDIS_IP:REDIS_PORT'
});
Has nobody gotten Unity SDK to work w/ self hosted Parse deployment?
If I use the prescribed code, that looks like this:
ParseClient.Initialize(new ParseClient.Configuration {
ApplicationId = "abc123",
Server = "http://exampe.ip.com/parse/"
});
i get a callstack that looks like this:
>
NullReferenceException: Object reference not set to an instance of an object
UnityEngine.WWW.FlattenedHeadersFrom (System.Collections.Generic.Dictionary`2 headers) (at C:/buildslave/unity/build/Runtime/Export/WWW.cs:118)
UnityEngine.WWW..ctor (System.String url, System.Byte[] postData, System.Collections.Generic.Dictionary`2 headers) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UtilsBindings.gen.cs:129)
Parse.Internal.HttpClient.GenerateWWWInstance (System.String uri, System.Byte[] bytes, System.Collections.Hashtable headerTable)
Parse.Internal.HttpClient+<>c__DisplayClass10+<>c__DisplayClass16.<ExecuteAsync>b__9 ()
Parse.PlatformHooks+<RunDispatcher>d__2e.MoveNext ()
UnityEngine.Debug:LogException(Exception)
Parse.<RunDispatcher>d__2e:MoveNext()
What am I missing?
I've debugged this and its due to a null value for the windowskey (aka ClientKey). Alter your initialization code to be the following and it should work:
ParseClient.Initialize(new ParseClient.Configuration {
ApplicationId = "abc123",
Server = "http://exampe.ip.com/parse/",
WindowsKey = '' //<== specify an empty string
});
in index.js:
....
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || 'myMasterKey', //Add your master key here. Keep it secret!
serverURL: process.env.SERVER_URL || 'http://localhost:1337/parse', // Don't forget to change to https if needed
clientKey: '', <=== possibly not needed, just to be sure
liveQuery: {
classNames: ["Scores", "Posts", "Comments"] // List of classes to support for query subscriptions
}
});