Looping Futures Exception. How to fix the cause - meteor

I'm working through the Discover Meteor book and after implementing the 'Errors' chapter, a typo caused an error an now the app is loop with the exception presented below.
My question is, how do I fix it or reset (I've tried 'meteor reset' but the exception loop persists)
W20140711-10:21:00.387(2)? (STDERR)
W20140711-10:21:00.388(2)? (STDERR) /Users/mwho/.meteor/tools/858c88b520/lib/node_modules/fibers/future.js:173
W20140711-10:21:00.390(2)? (STDERR) throw(ex);
W20140711-10:21:00.391(2)? (STDERR) ^
W20140711-10:21:00.479(2)? (STDERR) Error: allow: Invalid key: remote
W20140711-10:21:00.480(2)? (STDERR) at packages/mongo-livedata/collection.js:575
W20140711-10:21:00.492(2)? (STDERR) at Array.forEach (native)
W20140711-10:21:00.493(2)? (STDERR) at Function._.each._.forEach (packages/underscore/underscore.js:105)
W20140711-10:21:00.494(2)? (STDERR) at addValidator (packages/mongo-livedata/collection.js:573)
W20140711-10:21:00.496(2)? (STDERR) at Meteor.Collection.allow (packages/mongo-livedata/collection.js:613)
W20140711-10:21:00.496(2)? (STDERR) at app/collections/posts.js:3:7
W20140711-10:21:00.497(2)? (STDERR) at app/collections/posts.js:52:3
W20140711-10:21:00.498(2)? (STDERR) at /Users/mwho/microsope/.meteor/local/build/programs/server/boot.js:155:10
W20140711-10:21:00.500(2)? (STDERR) at Array.forEach (native)
W20140711-10:21:00.500(2)? (STDERR) at Function._.each._.forEach (/Users/mwho/.meteor/tools/858c88b520/lib/node_modules/underscore/underscore.js:79:11)
=> Exited with code: 8
Posts.js
Posts = new Meteor.Collection('posts');
Posts.allow({
update: ownsDocument,
remote: ownsDocument
});
Posts.deny({
update: function( userId, post, fieldNames ) {
// may only edit the following two fields:
return (_.without(fieldNames, 'url', 'title').length > 0);
}
});
Meteor.methods({
post: function(postAttributes) {
var user = Meteor.user(),
postWithSameLink = Posts.findOne({
url: postAttributes.url
});
// ensure the user is logged in
if (!user) throw new Meteor.Error(401, "You need to login to post new stories");
// ensure the post has a title
if (!postAttributes.title) throw new Meteor.Error(422, 'Please fill in a headline');
// check that there are no previous posts with the same link
if (postAttributes.url && postWithSameLink) {
throw new Meteor.Error(302,
'This link has already been posted', postWithSameLink._id);
}
// pick out the whitelisted keys
var post = _.extend(_.pick(postAttributes, 'url', 'title', 'message'), {
title: postAttributes.title + (this.isSimulation ? '(client)' : '(server)'),
userId: user._id,
author: user.username,
submitted: new Date().getTime()
});
//
// wait 5 seconds
if ( ! this.isSimulation ) {
var Future = Npm.require('fibers/future');
var future = new Future();
Meteor.setTimeout( function() {
future.return();
}, 5*1000);
future.wait();
}
var postId = Posts.insert(post);
return postId;
}
});

there is a typo in your code.
Posts.allow({
update: ownsDocument,
remote: ownsDocument
});
should be changed as
Posts.allow({
update: ownsDocument,
remove: ownsDocument
});

Related

"Request is not available" on apollo graphql query to withApiAuthRequired endpoint

I'm fairly new to graphql/apollo setup, and am stuck on the following issue:
My setup looks like this roughly:
Resolvers:
export const resolvers: Resolvers = {
Query: {
getUser: withApiAuthRequired(getUser)
}
};
async function getUser(req: any, res: any) {
try {
const { accessToken } = await getAccessToken(req, res);
console.log(accessToken);
} catch (error) {
console.error(error);
res.status(error.status || 500).end(error.message);
}
}
Client caller:
const data = await client.query({
query: gql`
query UsersQuery {
getUser
}
`
});
console.log(data);
The error I get:
Uncaught (in promise) Error: Request is not available
at new ApolloError (index.js?f0e4:29:1)
at eval (QueryManager.js?2692:596:1)
at both (asyncMap.js?bd9c:16:46)
at eval (asyncMap.js?bd9c:9:57)
at new Promise (<anonymous>)
at Object.then (asyncMap.js?bd9c:9:1)
at Object.eval [as next] (asyncMap.js?bd9c:17:1)
at notifySubscription (module.js?9653:132:1)
at onNotify (module.js?9653:176:1)
at SubscriptionObserver.next (module.js?9653:225:1)
at eval (iteration.js?aad9:4:50)
at Array.forEach (<anonymous>)
at iterateObserversSafely (iteration.js?aad9:4:1)
at Object.next (Concast.js?eb39:25:43)
at notifySubscription (module.js?9653:132:1)
at onNotify (module.js?9653:176:1)
at SubscriptionObserver.next (module.js?9653:225:1)
at eval (createHttpLink.js?2d67:103:1)
Thank you so much for the guidance!
try this one:
const data = await client.query({
query: gql `
query {
getUser
}
`
});
console.log(data);
I believe the issue is that I was trying to use withApiAuthRequired inside Resolvers. The argument to Resolvers needs to be an unwrapped function to work. I ended up just skipping the withApiAuthRequired wrapper and using getSession instead.

Firebase Cloud function for Push notification

I am able to send the push notification without delivery_receipt_requested. On adding the delivery_receipt_requested field, I am getting error.
I want to update a field in the database whenever the notification is delivered to the device from Firebase cloud function.
Error sending message: { Error: Invalid JSON payload received. Unknown
name "delivery_receipt_requested" at 'message': Cannot find field.
at FirebaseMessagingError.Error (native)
at FirebaseMessagingError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:39:28)
at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:85:28)
at new FirebaseMessagingError (/user_code/node_modules/firebase-admin/lib/utils/error.js:241:16)
at Function.FirebaseMessagingError.fromServerError (/user_code/node_modules/firebase-admin/lib/utils/error.js:271:16)
at /user_code/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:149:50
at process._tickDomainCallback (internal/process/next_tick.js:135:7) errorInfo: { code:
'messaging/invalid-argument',
message: 'Invalid JSON payload received. Unknown name "delivery_receipt_requested" at \'message\': Cannot find field.' },
codePrefix: 'messaging' }
my payload structure
var payload = {
delivery_receipt_requested:true,
notification: {
title: user,
body: snapshot2.val()
},
android: {
notification: {
sound: "default"
}
},
token: userToken
};
admin.messaging().send(payload)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
return 1;
})
.catch((error) => {
console.log('Error sending message:', error);
return 0;
});
return snapshot2.val()
}).catch(error => {
console.log("Error" + userToken2)
});

SimpleSchema is not a constructor

My app constantly crashes with this error. TypeError: SimpleSchema is not a constructor at attendances.js (imports/api/attendances/attendances.js:44:27). I've googled it and the StackOverflow solution doesn't work. I'm running simpl-schema and Collection2 Can anyone tell me whats wrong here?
import { Mongo } from 'meteor/mongo';
import SimpleSchema from 'simpl-schema';
const Attendances = new Mongo.Collection('attendances');
Attendances.debug = true;
Attendances.allow({
insert: () => true,
update: () => true,
remove: () => true,
});
Attendances.deny({
insert: () => false,
update: () => false,
remove: () => false,
});
const AttendancesSchema = new SimpleSchema({
createdAt: {
type: Date,
},
}, {
clean: {
filter: true,
autoConvert: true,
removeEmptyStrings: true,
trimStrings: true,
getAutoValues: true,
},
});
Attendances.attachSchema(AttendancesSchema);
export default Attendances;
This is the full error message in my terminal.
Path: ERROR MESSAGE
W20180620-21:07:11.542(10)? (STDERR) TypeError: SimpleSchema is not a constructor
W20180620-21:07:11.542(10)? (STDERR) at attendances.js (imports/api/attendances/attendances.js:44:27)
W20180620-21:07:11.543(10)? (STDERR) at fileEvaluate (packages/modules-runtime.js:339:7)
W20180620-21:07:11.543(10)? (STDERR) at require (packages/modules-runtime.js:238:16)
W20180620-21:07:11.543(10)? (STDERR) at publications.js (imports/api/userProfiles/server/publications.js:1:354)
W20180620-21:07:11.543(10)? (STDERR) at fileEvaluate (packages/modules-runtime.js:339:7)
W20180620-21:07:11.543(10)? (STDERR) at require (packages/modules-runtime.js:238:16)
W20180620-21:07:11.543(10)? (STDERR) at register-api.js (imports/startup/server/register-api.js:1:195)
W20180620-21:07:11.543(10)? (STDERR) at fileEvaluate (packages/modules-runtime.js:339:7)
W20180620-21:07:11.544(10)? (STDERR) at require (packages/modules-runtime.js:238:16)
W20180620-21:07:11.544(10)? (STDERR) at index.js (imports/startup/server/index.js:1:50)
W20180620-21:07:11.544(10)? (STDERR) at fileEvaluate (packages/modules-runtime.js:339:7)
W20180620-21:07:11.544(10)? (STDERR) at require (packages/modules-runtime.js:238:16)
W20180620-21:07:11.544(10)? (STDERR) at main.js (server/main.js:1:14)
W20180620-21:07:11.544(10)? (STDERR) at fileEvaluate (packages/modules-runtime.js:339:7)
W20180620-21:07:11.545(10)? (STDERR) at require (packages/modules-runtime.js:238:16)
W20180620-21:07:11.545(10)? (STDERR) at /Users/blakepascoe/Documents/dev/roll_call/.meteor/local/build/programs/server/app/app.js:1725:1
I tried the suggested fix in the comment by #bp123 that you should reset the Meteor project, and that fixed it for me too.
So I'm turning that comment into an answer:
Reset your project.
It does not seem impossible that a schema need to be added before any data is put in the database, but I'm very confused why this applies even for creating a Schema without attaching it to anything.

Socket hang up error in Cloud Functions for Firebase

I have a Cloud Function that is triggered by a Pub / Sub event. It uses request-promise to make multiple GET requests from an API I use for my data.
It works when running locally in the Cloud Functions Emulator, however in production I keep getting this error:
{ RequestError: Error: socket hang up
at new RequestError (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/errors.js:14:15)
at Request.plumbing.callback (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:87:29)
at Request.RP$callback [as _callback] (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:46:31)
at self.callback (/user_code/node_modules/request/request.js:185:22)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at Request.onRequestError (/user_code/node_modules/request/request.js:877:8)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketOnEnd (_http_client.js:346:9)
at emitNone (events.js:91:20)
at TLSSocket.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
name: 'RequestError',
message: 'Error: socket hang up',
cause:
{ Error: socket hang up
at createHangUpError (_http_client.js:254:15)
at TLSSocket.socketOnEnd (_http_client.js:346:23)
at emitNone (events.js:91:20)
at TLSSocket.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9) code: 'ECONNRESET' },
error:
{ Error: socket hang up
at createHangUpError (_http_client.js:254:15)
at TLSSocket.socketOnEnd (_http_client.js:346:23)
at emitNone (events.js:91:20)
at TLSSocket.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9) code: 'ECONNRESET' },
options:
{ method: 'GET',
uri: 'https://api.coinmarketcap.com/v2/ticker/?convert=BTC&start=0',
json: true,
callback: [Function: RP$callback],
transform: undefined,
simple: true,
resolveWithFullResponse: false,
transform2xxOnly: false },
response: undefined }
Any idea why I get this socket hang up error when my Cloud Function runs?
Edit: Here is what my cloud function code looks like:
const functions = require('firebase-functions');
// Import Admin SDK
var admin = require("firebase-admin");
var reqprom = require('request-promise');
admin.initializeApp(functions.config().firebase);
exports.minutely_tick =
functions.pubsub.topic('minutely-tick').onPublish((event) => {
console.log('This job runs every 5 minutes!');
getAllData()
.then((dataArray) => {
const ref = admin.database().ref(`myData/`);
ref.set(dataArray);
return console.log('dataArray length:', dataArray.length);
})
.catch((error) => {
return console.log('Caught error: ', error);
});
});
function getAllData() {
return new Promise((resolve, reject) => {
var promises = [];
var startInt = 0;
for (i = 0; i < 1000; i++) {
const options = {
method: GET,
uri: myUrlString,
json: true
}
promises.push(reqprom(options));
startInt += 100;
}
Promise.all(promises)
.then((dict) => {
var array = valuesFromDict(dict);
return resolve(array);
})
.catch((error) => {
return reject(error);
});
});
}
function valuesFromDict(dict) {
var values = Object.keys(dict).map((key) => {
return dict[key];
});
return values;
}
In summary, the function makes multiple API calls in a loop. And via promises I wait for all of them to complete. And then format that data into an array that I set to a Firebase Database reference.
You're not returning the final promise from your promise chain. Cloud Functions requires that you return a promise that resolves only when all of the async work is complete in your function.
return getAllData().then(...).catch(...)
i had a content filter in my computer, when i removed it the problem solved

ionic 2 Error 'ReferenceError: sqlitePlugin is not defined'

I'm been using the ionic 2 native sqlite plugin to make a basic app to capture and store images to the phones local storage. I keep getting an uncaught exception error (seemingly from the sql plugin) sometimes when i run the app on the genymotion emulator.
This normally happens when the app reloads when i'm using the -live parameter(ionic run android -c -l).
I also noticed that data which stored on the app doesn't appear(this again indicates that there is some problem loading the stored data when 'live reloading')
I've put the error i get on the console below:
The Console error message
[13:28:27] Starting 'html'...
[13:28:27] Finished 'html' after 42 ms
HTML changed: www/build/pages/home/home.html
HTML changed: www/build/pages/map-detail-component/map-detail-component.html
HTML changed: www/build/pages/map-page/map-page.html
0 298305 log Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
1 298474 group EXCEPTION: Error: Uncaught (in promise): ReferenceError: sqlitePlugin is not defined
2 298475 error EXCEPTION: Error: Uncaught (in promise): ReferenceError: sqlitePlugin is not defined
3 298476 error STACKTRACE:
4 298477 error Error: Uncaught (in promise): ReferenceError: sqlitePlugin is not defined
at resolvePromise (http://192.168.56.1:8100/build/js/zone.js:418:31)
at resolvePromise (http://192.168.56.1:8100/build/js/zone.js:403:17)
at http://192.168.56.1:8100/build/js/zone.js:451:17
at ZoneDelegate.invokeTask (http://192.168.56.1:8100/build/js/zone.js:225:37)
at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (http://192.168.56.1:8100/build/js/app.bundle.js:37360:41)
at ZoneDelegate.invokeTask (http://192.168.56.1:8100/build/js/zone.js:224:42)
at Zone.runTask (http://192.168.56.1:8100/build/js/zone.js:125:47)
at drainMicroTaskQueue (http://192.168.56.1:8100/build/js/zone.js:357:35)
at XMLHttpRequest.ZoneTask.invoke (http://192.168.56.1:8100/build/js/zone.js:297:25)
5 298478 groupEnd
6 298481 error Unhandled Promise rejection:, sqlitePlugin is not defined, ; Zone:, angular, ; Task:, Promise.then, ; Value:, [object Object], ReferenceError: sqlitePlugin is not defined
at http://192.168.56.1:8100/build/js/app.bundle.js:97420:13
at new ZoneAwarePromise (http://192.168.56.1:8100/build/js/zone.js:467:29)
at SQLite.openDatabase (http://192.168.56.1:8100/build/js/app.bundle.js:97419:16)
at new SqlService (http://192.168.56.1:8100/build/js/app.bundle.js:218:21)
at DebugAppView.Object.defineProperty.get (MyApp.template.js:18:67)
at DebugAppView._View_MyApp_Host0.injectorGetInternal (MyApp.template.js:35:79)
at DebugAppView.AppView.injectorGet (http://192.168.56.1:8100/build/js/app.bundle.js:31753:21)
at DebugAppView.injectorGet (http://192.168.56.1:8100/build/js/app.bundle.js:31945:49)
at ElementInjector.get (http://192.168.56.1:8100/build/js/app.bundle.js:31246:33)
at ElementInjector.get (http://192.168.56.1:8100/build/js/app.bundle.js:31249:48)
7 298519 log DEVICE READY FIRED AFTER, 1004, ms
8 298609 log Entering: map-page
9 298620 log ERROR: , {}
This goes away when i restart the emulator but then sometimes appears again after more usage.
I thought this could be due to the SQLite db being created before the plugin is imported but i've imported the plugin in my root app.ts file (shown below) (the whole app can be seen in this github repo)
Root app.ts
#Component({
template: '<ion-nav [root]="rootPage"></ion-nav>',
// Declare services
providers: [ SqlService ]
})
export class MyApp {
rootPage: any = MapPage;
constructor(platform: Platform) {
platform.ready().then(() => {
StatusBar.styleDefault();
});
}
}
ionicBootstrap(MyApp);
I've confined any use of the plugin to an sqlService (shown below)
SQL Service
import { Injectable } from '#angular/core';
import 'rxjs/add/operator/map';
import { SQLite} from 'ionic-native';
#Injectable()
export class SqlService {
private db: SQLite;
private isOpen: boolean;
public constructor() {
if(!this.isOpen){
this.db = new SQLite();
this.db.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
this.db.executeSql("CREATE TABLE IF NOT EXISTS places (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, img TEXT)", []).then((data) => {
console.log("TABLE CREATED: " + data);
}, (error) => {
console.log("Unable to execute SQL" + error);
});
this.isOpen=true;
});
}
}
public add(title: string, base64Img: string) {
return new Promise((resolve, reject) => {
this.db.executeSql("INSERT INTO places (title, img) VALUES ( '"+ title +"', '"+ base64Img +"')", [])
.then((data) => {
resolve(data);
}, (error) => {
reject(error);
});
});
}
// Remove individual Location
public remove(id: number){
return new Promise((resolve, reject) => {
this.db.executeSql("DELETE FROM places WHERE id = "+ id +";", [])
.then((data) => {
resolve(data);
}, (error) => {
reject(error);
});
});
}
public locDetail(id: number){
return new Promise((resolve, reject) => {
this.db.executeSql("SELECT * FROM places WHERE id = "+ id +";",[])
.then((data) => {
if(data.rows.length===1){
// console.log("ttitle: " + data.rows.item(0).title + " id: " + data.rows.item(0).id + " img: " + data.rows.item(0).img );
let place = [];
place.push({
id: data.rows.item(0).id,
title: data.rows.item(0).title,
img: data.rows.item(0).img
});
resolve(place);
}
}, (error) => {
reject(error);
});
});
}
// Refresh and initialise the places object
public refresh() {
return new Promise((resolve, reject) => {
this.db.executeSql("SELECT * FROM places", []).then((data) => {
let place = [];
if (data.rows.length > 0) {
for (var i = 0; i < data.rows.length; i++) {
place.push({
id: data.rows.item(i).id,
title: data.rows.item(i).title,
img: data.rows.item(i).img
});
}
}
resolve(place);
}, (error) => {
reject(error);
});
}
);
}
}
I recently had the same problem, make sure you check if the platform is ready also in your service. Import "Platform" from "ionic-angular" and execute your sqlite interaction code in the promise.then method.
I am using IOS and get the same error 'ReferenceError: sqlitePlugin is not defined'.
As the sqlite does not work when testing in Chrome browser I tried the ionic upload CLI function. Then got the same error.
I came across this issue on Github.
After using setTimeout it works in the Ionic view app on IOS:
setTimeout(function() {
let db = new SQLite();
db.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
db.executeSql("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT)", {}).then((data) => {
console.log("TABLE CREATED: ", data);
self.dummy = data
}, (error) => {
console.error("Unable to execute sql", error);
self.dummy = error;
})
}, (error) => {
console.error("Unable to open database", error);
self.dummy = error;
});
}, 2000);
please run your projeect in emulator/simulator or android device/ios device.it's not work on browser.

Resources