getting error with ember-fire: Assertion Failed: You must include an 'id' for undefined in an object passed to 'push' - emberfire

I have a sample notebook app that works with ember-cli's HTTP mocks and also my rails backend using ActiveModelSerializer.
When I hook it to firebase with ember-fire, I am able to register a user (I see it in the dashboard) but when I try to retrieve it by email, I get the following warning:
WARNING: Encountered "0" in payload, but no model was found for model name "0" (resolved model name using ui#serializer:application:.modelNameFromPayloadKey("0"))
then this error:
Error: Assertion Failed: You must include an 'id' for undefined in an object passed to 'push'
at new Error (native)
at Error.EmberError (http://localhost:4200/assets/vendor.js:24735:21)
at assert (http://localhost:4200/assets/vendor.js:14636:13)
at Object.assert (http://localhost:4200/assets/vendor.js:22037:34)
at ember$data$lib$system$store$$Service.extend._pushInternalModel (http://localhost:4200/assets/vendor.js:75316:15)
at ember$data$lib$system$store$$Service.extend.push [as _super] (http://localhost:4200/assets/vendor.js:75302:34)
at push (http://localhost:4200/assets/vendor.js:94940:38)
at superWrapper [as push] (http://localhost:4200/assets/vendor.js:30984:22)
at http://localhost:4200/assets/vendor.js:70210:27
at Object.Backburner.run (http://localhost:4200/assets/vendor.js:9707:25)
I am querying the store using:
export default Ember.Route.extend({
actions: {
login: function() {
this.store.query('user', {
email: this.controller.get('email')
}).then((users) => {
if(users.get('length') === 1) {
var user = users.objectAt(0);
this.controllerFor('application').set('user',user);
this.transitionTo('notebooks', user.get('id'));
}
else {
console.log('unexpected query result');
}
});
}
}
});
Digging in, I can see by setting breakpoint at finders.js#157 I am about to
store._adapterRun(function () {
var payload = normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, 'query');
//TODO Optimize
records = store.push(payload);
});
push the payload. The adapter payload inspects to
adapterPayload: Array[1]
0: Object
email: "test#test.com"
first_name: "Test"
id: "-K1oINClDw2ylQLww7-p"
last_name: "User"
which is my user. So all's good except for the trace. Not sure about that ID but I am new to firebase; maybe it's ok. It matches what I see in my dashboard.
I haven't done anything special with my serializer -- it's vanilla.
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
});
AFAIK I am using the latest & greatest -- here's bower.json
{
"name": "ui",
"dependencies": {
"ember": "2.1.0",
"ember-cli-shims": "ember-cli/ember-cli-shims#0.0.4",
"ember-cli-test-loader": "ember-cli-test-loader#0.1.3",
"ember-data": "2.1.0",
"ember-load-initializers": "ember-cli/ember-load-initializers#0.1.7",
"ember-qunit": "0.4.9",
"ember-qunit-notifications": "0.0.7",
"ember-resolver": "~0.1.18",
"jquery": "^2.1.4",
"loader.js": "ember-cli/loader.js#3.2.1",
"qunit": "~1.18.0",
"foundation": "~5.5.3",
"bootstrap": "~3.3.5",
"showdown": "~1.3.0",
"firebase": "^2.1.0"
}
}
and my dev dependencies in package.json
"devDependencies": {
"body-parser": "^1.14.1",
"broccoli-asset-rev": "^2.1.2",
"ember-cli": "1.13.8",
"ember-cli-app-version": "1.0.0",
"ember-cli-babel": "^5.1.3",
"ember-cli-dependency-checker": "^1.0.1",
"ember-cli-htmlbars": "1.0.1",
"ember-cli-htmlbars-inline-precompile": "^0.3.1",
"ember-cli-ic-ajax": "0.2.1",
"ember-cli-inject-live-reload": "^1.3.1",
"ember-cli-qunit": "^1.0.0",
"ember-cli-rails-addon": "0.0.12",
"ember-cli-release": "0.2.3",
"ember-cli-showdown": "2.5.0",
"ember-cli-sri": "^1.0.3",
"ember-cli-uglify": "^1.2.0",
"ember-data": "2.1.0",
"ember-disable-proxy-controllers": "^1.0.0",
"ember-export-application-global": "^1.0.3",
"emberfire": "1.6.0",
"express": "^4.13.3",
"glob": "^4.5.3",
"morgan": "^1.6.1",
"nedb": "^1.2.1"
}
Any pointers/help/guidance would be great! I am also new to ember too, so maybe I am missing the obvious?

You need a type key to be returned from your backend, rather than just sending an array. This lets Ember Data know what type of model you're pushing to the store. Your payload should look like this:
users: [
{
email: "test#test.com",
id: "abcdefg"
(...)
}
]
instead of this
[
{
email: "test#test.com",
id: "abcdefg"
(...)
}
]
Alternatively you can explicitly pass in the type and data:
store.push("user", store.normalize("user", response[0]));
(where response is still the array)

Related

Serverless fails with "You may need an appropriate loader to handle this file type " when external module uses Array.isArray()

When I run sls deploy, I get the following error
Serverless: Bundling with Webpack...
ERROR in /Users/pgonzalez/myapps/happy-soup-bulk-service/node_modules/sfdc-happy-api/lib/rest.js 258:54
Module parse failed: Unexpected token (258:54)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
...
| function isAccessError(jsonResponse){
|
> if(Array.isArray(jsonResponse) && jsonResponse[0]?.message == `Cannot retrieve documents in a user's private folder; move the document to a named folder`){
| return true;
| }
The arrow points to the call of Array.isArray and that is line 258 of the external module, which is the line referenced in the error.
If I remove the import of the external module, the error goes away
import bulkDependecy from 'sfdc-dependency-api-bulk';
What's weird is that I can use Array.isArray() directly on the handler
//import bulkDependecy from 'sfdc-dependency-api-bulk';
async function getUsage(event, context) {
const {ids,connection} = event.body;
// THIS DOESN'T FAIL
Array.isArray(['true']);
//let result = await bulkDependecy.getUsage(ids,connection);
return {
statusCode: 200,
body: 'result'
};
}
export const handler = getUsage;
Here's my serverless.yml
service:
name: happy-soup-bulk-service
plugins:
- serverless-bundle
- serverless-pseudo-parameters
provider:
name: aws
runtime: nodejs12.x
memorySize: 256
stage: ${opt:stage, 'dev'}
region: eu-west-1
functions:
createAuction:
handler: src/handlers/getUsage.handler
events:
- http:
method: POST
path: /usage
And my package.json
{
"name": "happy-soup-bulk-service",
"version": "1.0.0",
"description": "Codingly template for Serverless Framework projects",
"author": "Ariel Weinberger <ariel#codingly.io>",
"license": "MIT",
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-es2015": "^6.0.15",
"babel-polyfill": "^6.23.0",
"babel-preset-env": "^1.6.0",
"serverless-bundle": "^1.3.3",
"serverless-pseudo-parameters": "^2.5.0",
"webpack": "^4.35.2"
},
"dependencies": {
"aws-sdk": "^2.639.0",
"sfdc-dependency-api-bulk": "1.0.0"
}
}

Agenda | TimeoutOverflowWarning

Node.js Version: v12.13.1.
OS: Microsoft Windows 10 Pro, Version: 10.0.18362 Build 18362
NPM packages:
"agenda": "^2.0.2",
"appmetrics-dash": "^5.0.0",
"avro-schema-registry": "^1.5.1",
"avsc": "^5.4.16",
"await-to-js": "^2.1.1",
"bluebird": "^3.5.3",
"body-parser": "^1.18.3",
"dd-trace": "^0.12.1",
"debug": "^4.1.0",
"express": "^4.16.4",
"express-server-status": "^1.0.3",
"express-status-monitor": "^1.2.6",
"json-2-csv": "^3.5.2",
"kafkajs": "^1.11.0",
"lodash": "^4.17.11",
"moment": "^2.24.0",
"mongodb": "^3.1.8",
"mongoose": "^5.3.3",
"mongoose-auto-increment": "^5.0.1",
"qs": "6.9.0",
"request": "^2.88.0",
"request-promise": "^4.2.2",
"sha256": "^0.2.0",
"slack-node": "^0.1.8",
"socket.io": "^2.2.0"
I was running only agenda jobs. Almost all jobs are syncing data from other API's and saving all data to MongoDB. Sometimes after some time when I start the project, I get this error:
(node:26128) TimeoutOverflowWarning: 2591699977 does not fit into a 32-bit signed integer.
Timeout duration was set to 1.
at new Timeout (internal/timers.js:156:15)
at setTimeout (timers.js:142:19)
at jobProcessing (C:\Users\mailb\OneDrive\Desktop\DST\custom-market\node_modules\agenda\lib\utils\process-jobs.js:258:7)
at C:\Users\mailb\OneDrive\Desktop\DST\custom-market\node_modules\agenda\lib\utils\process-jobs.js:217:9
at C:\Users\mailb\OneDrive\Desktop\DST\custom-market\node_modules\agenda\lib\agenda\find-and-lock-next-job.js:81:7
at C:\Users\mailb\OneDrive\Desktop\DST\custom-market\node_modules\agenda\node_modules\mongodb\lib\utils.js:414:17
at C:\Users\mailb\OneDrive\Desktop\DST\custom-market\node_modules\agenda\node_modules\mongodb\lib\utils.js:401:11
at ClientSession.endSession (C:\Users\mailb\OneDrive\Desktop\DST\custom-market\node_modules\mongodb-core\lib\sessions.js:129:41)
at executeCallback (C:\Users\mailb\OneDrive\Desktop\DST\custom-market\node_modules\agenda\node_modules\mongodb\lib\utils.js:397:17)
at handleCallback (C:\Users\mailb\OneDrive\Desktop\DST\custom-market\node_modules\agenda\node_modules\mongodb\lib\utils.js:128:55)
at C:\Users\mailb\OneDrive\Desktop\DST\custom-market\node_modules\agenda\node_modules\mongodb\lib\operations\collection_ops.js:558:12
at handleCallback (C:\Users\mailb\OneDrive\Desktop\DST\custom-market\node_modules\agenda\node_modules\mongodb\lib\utils.js:128:55)
at C:\Users\mailb\OneDrive\Desktop\DST\custom-market\node_modules\agenda\node_modules\mongodb\lib\operations\db_ops.js:516:5
at C:\Users\mailb\OneDrive\Desktop\DST\custom-market\node_modules\mongodb-core\lib\connection\pool.js:532:18
at processTicksAndRejections (internal/process/task_queues.js:75:11)
I ended up to install the "agenda": "2.2.0" version.
It reveals that i made a mistake in one of my instance where i didn't throw error, and it make the job infinitely process.
I advise you to try the same and run your server with --trace-warnings.
npm install --save agenda#2.2.0
node --trace-warnings yournodejsapp
Then, just see the logs and it will output where the error happen. Fix the error and you will be good :-)
FYI,
If you look at the agenda source code where the error is happenning.
// If the 'nextRunAt' time is older than the current time, run the job
// Otherwise, setTimeout that gets called at the time of 'nextRunAt'
if (job.attrs.nextRunAt < now) {
debug('[%s:%s] nextRunAt is in the past, run the job immediately', job.attrs.name, job.attrs._id);
runOrRetry();
} else {
const runIn = job.attrs.nextRunAt - now;
debug('[%s:%s] nextRunAt is in the future, calling setTimeout(%d)', job.attrs.name, job.attrs._id, runIn);
setTimeout(runOrRetry, runIn);
}
/**
* Internal method that tries to run a job and if it fails, retries again!
* #returns {undefined}
*/
async function runOrRetry() {
if (self._processInterval) {
const job = jobQueue.pop();
const jobDefinition = definitions[job.attrs.name];
if (jobDefinition.concurrency > jobDefinition.running && self._runningJobs.length < self._maxConcurrency) {
// Get the deadline of when the job is not supposed to go past for locking
const lockDeadline = new Date(Date.now() - jobDefinition.lockLifetime);
// This means a job has "expired", as in it has not been "touched" within the lockoutTime
// Remove from local lock
// NOTE: Shouldn't we update the 'lockedAt' value in MongoDB so it can be picked up on restart?
if (job.attrs.lockedAt < lockDeadline) {
debug('[%s:%s] job lock has expired, freeing it up', job.attrs.name, job.attrs._id);
self._lockedJobs.splice(self._lockedJobs.indexOf(job), 1);
jobDefinition.locked--;
jobProcessing();
return;
}
// Add to local "running" queue
self._runningJobs.push(job);
jobDefinition.running++;
// CALL THE ACTUAL METHOD TO PROCESS THE JOB!!!
debug('[%s:%s] processing job', job.attrs.name, job.attrs._id);
job.run()
.catch(error => [error, job])
.then(job => processJobResult(...Array.isArray(job) ? job : [null, job])); // eslint-disable-line promise/prefer-await-to-then
// Re-run the loop to check for more jobs to process (locally)
jobProcessing();
} else {
// Run the job immediately by putting it on the top of the queue
debug('[%s:%s] concurrency preventing immediate run, pushing job to top of queue', job.attrs.name, job.attrs._id);
enqueueJobs(job);
}
}
}

False positives for `no-unused-vars`

I'm getting a lot of incorrect ESLint/TS warnings saying enum cases are "Assigned a value but never used" or that imports are "defined but never used". Here's some code.
All the imports are saying they're defined but never used (though you can see they are in the types at the bottom).
All the enum cases are saying they're "Assigned a value but never used", and you can see that they are indeed used in all the action types.
I will note, though, that PARAMETER_CHANGE_FAILED also says "Unused readonly field PARAMETER_CHANGE_FAILED" which is actually true, that case is never actually used in my project.
import {ThunkAction, ThunkDispatch} from "redux-thunk";
import {AppState} from "../reducers/index.reducer";
export type ChangeParameterAction = {
type: MyActionType.PARAMETER_CHANGED,
parameter: ParameterName,
value: any
}
export type SetParametersAction = {
type: MyActionType.PARAMETERS_SET,
settings: { [name: string]: any }
}
export type ActiveTabAction = {
type: MyActionType.TAB_CHANGED,
tab: Tab
}
export type ErrorAction = {
type: MyErrorType,
error: Error
}
export enum MyErrorType{
ERROR = 'ERROR',
PARAMETER_CHANGE_FAILED = 'PARAMETER_CHANGE_FAILED',
}
export enum MyActionType{
TAB_CHANGED = 'TAB_CHANGED',
PARAMETER_CHANGED = 'PARAMETER_CHANGED',
PARAMETERS_SET = 'PARAMETERS_SET',
}
export type SettingsAction = ChangeParameterAction | SetParametersAction;
export type FirmmAction =
| ActiveTabAction
| UpdateActiveSeriesAction
| UpdateStudyAction
| UpdateDataAction
| SettingsAction
| ErrorAction
export type MyThunkAction = ThunkAction<void, AppState, {}, MyAction>
export type MyThunkDispatch = ThunkDispatch<{}, {}, MyAction>
In another file, I import pretty much everything from the file above, and use them all (Webstorm's 'Optimize Imports' has been run) but all the types are showing as never used. Interestingly, two of the imported enums aren't giving this false positive error, although one of them is.
I can set no-unused-vars to off in my eslint config, but I'd rather have it actually work properly.
Here's some config info:
// eslintrc
module.exports = {
env: {
browser: true,
es6: true,
},
extends: [
'react-app',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parser: '#typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 2018,
sourceType: 'module',
},
plugins: [
'react',
'#typescript-eslint',
],
rules: {
// TODO: Adding this rule
// "no-unused-vars": "off"
},
};
// package.json dependencies
...
"eslint-config-react-app": "^3.0.5",
"eslint-loader": "2.1.1",
"eslint-plugin-flowtype": "2.50.1",
"eslint-plugin-typescript": "^1.0.0-rc.3",
...
// package.json devDependencies
...
"#typescript-eslint/eslint-plugin": "^2.7.0",
"#typescript-eslint/parser": "^2.7.0",
"eslint": "^6.6.0",
"eslint-config-airbnb": "^18.0.1",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.16.0",
"eslint-plugin-react-hooks": "^1.7.0",
...
In my case, it helped to use #vue/eslint-config-typescript/recommended configuration.
I also had to install:
eslint-config-typescript (v5, previously I had v4)
#typescript-eslint/eslint-plugin
#typescript-eslint/parser
As suggested here: eslint-config-typescript, I used the following config:
extends: [
'plugin:vue/essential',
'#vue/typescript/recommended', // corrects the 'no-unused-vars'
'#vue/prettier',
'#vue/prettier/#typescript-eslint', // for prettier to work
],

Access swagger path parameters from middleware

How can I retrieve a swagger path parameter from nodejs?
The swagger definition:
/objects/{id}:
x-swagger-router-controller: object.controller
get:
summary: Get object
operationId: getObject
consumes:
- application/json
parameters:
- in: path
name: id
type: string
required: true
What I've tried:
req.swagger.params['id'].value
req.query.id
Is there any dependency I need? My current dependencies are
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.12.3",
"morgan": "^1.9.1",
"swagger-express-mw": "^0.7.0",
"swagger-tools": "^0.10.4",
"swagger-ui": "^3.20.5",
"web3": "^1.0.0-beta.36"
}
Change this: req.swagger.params['id'].value --> req.swagger.params.id.value.
If you're using express framework and express router you can access request parameters by their name. For example this /objects/{id}: path parameter can be accessed like: req.params.id

Gulp. Node V4. Typeerror (only on watch): Path must be a string

All tasks executes well, except watchh where use function gulp.watch(). I really don't know what should I do. Over the internet same error issued with NodeJS v6. But I have latest 4 major ver.
Have a gulp file
// gulp declarations
var gulp = require('gulp'),
pug = require('gulp-pug'),
copy = require('gulp-copy'),
concat = require('gulp-concat'),
sass = require('gulp-sass'),
uglifycss = require('gulp-uglifycss'),
rename = require('gulp-rename');
// other declaration
var sq = require('streamqueue'); //allow to write results into stream, rather file output
/*
* Complete result in a single css file for public using. */
gulp.task('fincss', function () {
var convertFromScssToCssAndConcat =
gulp.src('./src/sass/*.scss')
.pipe(sass().on('error', sass.logError));
var minifyAndConcatExistingCss =
gulp.src('./src/css/*.css');
return sq({objectMode: true},
minifyAndConcatExistingCss, convertFromScssToCssAndConcat)
.pipe(concat('final.min.css'))
.pipe(uglifycss())
.pipe(gulp.dest('./public/css/'));
});
gulp.task('pug', function () {
return gulp.src(['src/pug/*.pug', '!src/pug/component_*.pug'])
.pipe(pug())
.pipe(gulp.dest('public/'));
});
gulp.task('watchh', function () {
gulp.watch('./src/css/*.css', ['fincss']);
gulp.watch('./src/sass/*.scss', ['fincss']);
gulp.watch('./src/pug/*.pug', ['pug']);
});
npm dependencies
"devDependencies": {
"gulp": "^3.9.1",
"gulp-concat": "^2.6.0",
"gulp-pug": "^3.0.4",
"gulp-rename": "^1.2.2",
"gulp-sass": "^2.3.2",
"gulp-uglify": "^2.0.0",
"gulp-uglifycss": "^1.0.6",
"gulp-watch": "^4.3.9",
"semantic-ui-css": "^2.2.2",
"streamqueue": "^1.1.1"
},
Where am I wrong?
The answer has been found only by gulp-watch plugin.
First, add
watch = require('gulp-watch');
Second, the Task is
gulp.task('watch', ['fincss'], function () {
watch([<pathes_here>], function () {
gulp.run('fincss');
});
});
Thanks for attention to everyone.

Resources