moment returns wrong value - node.js

I'm parsing a date using momentjs:
var startDate = moment.utc('2016-02-20T07:00:00.000Z')
If I'm writing startDate.toISOString() to the console, I get this:
2016-02-19T21:00:00.000Z
The startDate object looks like this:
{ [Number: 1455915600000]
_isAMomentObject: true,
_i: '2016-02-20T07:00:00.000Z',
_f: 'YYYY-MM-DDTHH:mm:ss.SSSSZ',
_tzm: -0,
_isUTC: true,
_pf:
{ empty: false,
unusedTokens: [],
unusedInput: [],
overflow: -1,
charsLeftOver: 0,
nullInput: false,
invalidMonth: null,
invalidFormat: false,
userInvalidated: false,
iso: true },
_locale:
Locale {
_ordinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal: [Function],
_abbr: 'en',
_ordinalParseLenient: /\d{1,2}(th|st|nd|rd)|\d{1,2}/ },
_d: Fri Feb 19 2016 22:00:00 GMT+0100 (CET),
_isValid: true,
_offset: 0 }
Where does this difference result from?

Related

agenda scheduling defaulting nextRunAt to next year

I am trying to schedule jobs usign the agenda library. I've done this:
await this.agenda.start()
this.agenda.define(scheduler.id, { lockLifetime: 10000 }, (job, done) => {
console.log('Hello world!')
//some logic using values on job variable
done()
})
const result = await this.agenda.every(scheduler.cron, scheduler.id, scheduler, { startDate: new Date() })
await this.agenda.start() //i added start here too just in case
console.log(result)
That last console.log shows that the job was created successfully and it even saves on database, but the nextRunAt defaults to 1st of january 2022 for some reason (as seen on the full object below). I tried adding the startDate on the every() call but it still shows 2022 and i have no idea why. No matter what cron i send it still doesnt work. The only param i send to Agenda constructor is the database, nothing about when to start.
Thanks!
Job {
agenda: Agenda {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
_findAndLockNextJob: [Function: findAndLockNextJob],
_name: undefined,
_processEvery: 5000,
_defaultConcurrency: 5,
_maxConcurrency: 20,
_defaultLockLimit: 0,
_lockLimit: 0,
_definitions: { '61af764f8f26fb369c76b571': [Object] },
_runningJobs: [],
_lockedJobs: [],
_jobQueue: JobProcessingQueue { _queue: [] },
_defaultLockLifetime: 600000,
_sort: { nextRunAt: 1, priority: -1 },
_indices: { name: 1, nextRunAt: 1, priority: -1, lockedAt: 1, disabled: 1 },
_isLockingOnTheFly: false,
_isJobQueueFilling: Map(0) {},
_jobsToLock: [],
_ready: Promise { undefined },
_db: MongoClient {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
topology: [Topology],
[Symbol(kCapture)]: false,
[Symbol(options)]: [Object: null prototype]
},
_mdb: Db { s: [Object] },
_collection: Collection { s: [Object] },
_processInterval: Timeout {
_idleTimeout: 5000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 28573,
_onTimeout: [Function: bound processJobs],
_timerArgs: undefined,
_repeat: 5000,
_destroyed: false,
[Symbol(refed)]: true,
[Symbol(kHasPrimitive)]: false,
[Symbol(asyncId)]: 221,
[Symbol(triggerId)]: 0
},
[Symbol(kCapture)]: false
},
attrs: {
name: '61af764f8f26fb369c76b571',
data: {
//stuff that i use here
},
priority: 0,
type: 'single',
nextRunAt: 2022-01-01T03:00:00.000Z, //next run at 2022
repeatInterval: '* * * 1 *',
repeatTimezone: null,
startDate: 2021-12-07T14:57:19.394Z,
endDate: null,
skipDays: null,
_id: new ObjectId("61af764fcb12102f92e637dc")
}
}
Using crontab i noticed that the problem was my cron job that was going to run on the 1st day of the next month, nothing to do with the lib. Now with a correct cron its working as intended

npm pdfjs creates corrupted PDF files

I am trying to create PDF files with the npm library pdfjs https://www.npmjs.com/package/pdfjs . Once all the elements (paragraphs) of the file are append to the doc I create the file, but when opening it I have a message it says is corrupted.
When I use doc.end() to finish the document, says there is no function. So I used a promise and tried to use later on the information. But even when I get an object with all the data, I can't manage to make the .pdf file not corrupted.
This is the code I'm using:
const pdf = require('pdfjs')
const fs = require('fs')
function createPDF(data, options){
return new Promise((resolve, reject) => {
var doc = new pdf.Document({ font: require('pdfjs/font/Helvetica') });
var header = doc.header().table({ widths: [null, null], paddingBottom: 1*pdf.cm }).row()
header.cell().image('/images/logo.png', { height: 2*pdf.cm })
header.cell().text({ textAlign: 'right' })
.add('Example.')
.add('https://www.example.com', {
link: 'https://www.example.com',
underline: true,
color: 0x569cd6
})
doc.footer()
.pageNumber(async function(curr, total) { return curr + ' / ' + total }, { textAlign: 'center' });
resolve(doc)
});
}
var doc = createPDF();
doc.then(async (data) => {
data.pipe(fs.createWriteStream('output.pdf'))
console.log(data);
await data.end();
})
Log Data:
Document {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes:
WriteStream {
_writableState: [Object],
writable: true,
domain: null,
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
path: 'output.pdf',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
autoClose: true,
pos: undefined,
bytesWritten: 0 },
pipesCount: 1,
flowing: true,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: true,
paused: false,
emitClose: true,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ read: { [Function: bound onceWrapper] listener: [Function] },
end: { [Function: bound onceWrapper] listener: [Function: onend] },
data: [Function: ondata] },
_eventsCount: 3,
_maxListeners: undefined,
version: '1.6',
info: { id: '34d7f55c-5961-4caf-9814-1902b98bee3c' },
width: 595.296,
height: 841.896,
_nextObjectId: 4,
_xref: PDFXref { objects: [], trailer: null },
_reading: false,
_length: 0,
_pending:
[ [Function],
[ [Function], [Array], [Array], [Function] ],
[Function],
[Function],
[Function],
[Function],
current: Promise { <pending> } ],
defaultFont:
AFMFont {
_data:
{ fontName: 'Helvetica',
fullName: 'Helvetica',
familyName: 'Helvetica',
italicAngle: 0,
characterSet: 'ExtendedRoman',
fontBBox: [Array],
underlinePosition: -100,
underlineThickness: 50,
capHeight: 718,
xHeight: 523,
ascender: 718,
descender: -207,
kerning: [Object],
widths: [Array] },
lineGap: 231,
parent: [Circular] },
defaultFontSize: 11,
defaultColor: [ 0, 0, 0 ],
defaultLineHeight: 1.15,
_fonts: { '/F1': { f: [Object], o: [Object] } },
_xobjects: {},
_pageFonts: {},
_annotations: [],
_aliases: AliasGenerator { nextId: { F: 2 }, blocked: Set {} },
_mapping: WeakMap {},
_currentContent: null,
_contents: [],
_contentObjCreator: null,
_finalize: [],
_template: null,
_footer: null,
_header: null,
paddingTop: 20,
paddingBottom: 20,
paddingLeft: 20,
paddingRight: 20,
_cursor:
Cursor {
width: 555.296,
height: 801.896,
x: 20,
startX: 20,
y: 821.896,
startY: 821.896,
_bottom: 20,
bottomOffset: 0 },
_pages: [ toString: [Function] ],
_pagesObj:
PDFObject {
id: 2,
rev: 0,
properties: PDFDictionary { dictionary: [Object] },
reference: PDFReference { object: [Getter] },
content: 'stream\n!!!Djz!WW3#D/OH9;Fa%r=BSfM#MB(Z!#knQ!$hOd#:O#tzzzz!!!!"zz!!)`D!!*\'"!!(J"z\'&psr`WC#h?J?20S8TbAzzzzzzz!!!!1A7]gl!!!
$f!!!"E#TZc:!!!&8!!!!5#T65m!!!&L!!!95B2hbr!!!&L!!!95E`>q(!!!&L!!!95A8Pjf!!!>`!!!"TB38;?!!!#>!!!!5CisT/!!!#R!!!!5D.R-s!!!#f!!!!E#V]q)!!!A5!
!!!5E`cIJ!!!AI!!!!5FCerq!!!A]!!!!-G\'.A,!!!Ai!!!"SGB#eG!!!CG!!!!5#rQI1!!!C[!!!!X#q]:]!!!D>!!!!MA7]glz!!!!#F&GLp+A#!h2DI3M2D$[90d\'qA#:O\'q
F(8WpARkc#zzzzzzzzzzzzzzzzzzzz=BSfMz!!":;!!!O_!!\'IR#s)g8z!!!-%!!!!&!"&]:!#,DN!$2+b!%7h!!&=O5!\':0G!(?l[!)ESo!*K;.!+Q"B!,V^V!-\\Ej!.b-)!/g
i=!0mPQ!1s7e!3#t$!3uU6!5&<J!6,#^!71_r!8#M3!9F4H!:U!^!;cct!=&W7!>>JO!?V=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Z8%"Wrf>EX6H]jXO+(;XgkMcY+`$7YD]UbY][28Z!aifZ:hL?ZT,:oZmE)L[1fs*[K3g^[d^b>\\)=c!\\C%iZ\\\
\bp>]!].&];N:b]UQSL]oTl7^4a6#^O!Zf^i7*U_.UUE_I(17_cXh+`)4Iu`Cn1k`^[tca$Ib\\a?#VWaZ#PSauIPQb;RPPbVdVPbr*bRc8NtVcSs1[coKIad6,gjdQc0rdmV[)e4J
05eP=ZBelC;Rf3HqcfOWXufkf#3g323IgOS&_gkso!h3Qn;hP/mVhlkrri4\\);iQU:[inNL\'j6PcIjS\\+mjpgI=k9&ldkVDA7ksjpal<EQ8lYu1em"Xm>m#<Smm^2FJn\'(9\'n
E\'1\\nc/0=o,7.toJH3Wohb><p20O#pPS_`po+!Jq8`>5qWIa"r!3.er#.]Vr_*7Gs)%f9A7]glz!!!!O8OYuh2DI3M2D$[90d&kqAmoguF<FIO66JX6Ci=H:+B*5f#q?c7+ELFN6
3$uczzzzzzzzzzzzzzzzzzz=BSfMz!!$Jr!!\'K^!!!ki=BSfMzz!)NXqzD.R-sz!!!!"zzzzz!!!!#=BSfMz!!!"j!!!"p!!!"S=BSfMz!!$r3!!#"O!!!+_F(o80z6W-l+A7]glz
!!!!N;IsHOEb0,uAKY#fATqj+B-9Q[DIdI\'Bl#l3Bl5%b77/1U0f_-M/M\\n4zzzzzzzzzzzzzzzzzzzz=BSfMz!!)`D!!*\'"!!(J"FCf]=z6Z6phEbT0"F<F.mFCfK1#<?4%DII
?(6Z6dZEZd_fDKB`:FD5l7/0H]%0KB+5F(R3`z!!*Kr!!!2[s8V[;!!!7g!!)tYs8Vtis8W%l!!!,U!!\'fW~>\nendstream\n' },
_currentColorSpace: '/CS1',
_doc: [Circular],
_parent: [Circular],
_ended: false,
_current:
Footer {
_doc: [Circular],
_parent: [Circular],
_cursor:
ClonedCursor {
width: 555.296,
height: 801.896,
bottomOffset: 0,
startX: 20,
startY: 821.896,
_root: [Object] },
_ended: false,
_current: null,
_pending:
[ [Function],
[Array],
[Function],
[Function],
[Function],
[Function],
current: [Object] ],
_objects: [],
_pageNumbers: [] } }
It looks like the content is there but can't manage to get it. And whe await data.end(); is run, it show the next error log show:
TypeError: Invalid value used as weak map key TypeError: Invalid value used as weak map key
at WeakMap.set (native)
at Document._useXObject (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/document.js:255:21)
at module.exports (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/image/render.js:16:23)
at _pending.push (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/fragment.js:143:30)
at Document._next (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/document.js:169:36)
at _pending.current.next.then (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/document.js:172:19)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
The expected output is a correct .pdf file. But even when my output is a .pdf file, it is corrupted.
Unable to open document “file:///home/developer1/Projects/pdf/output.pdf”.
Error when trying to open the file:
PDF document is damaged
If you can help me either solving this, or with a library of your knowledge that it works will be bomb.
I could not found a solution for the pdfjs library. But I found a library that worked better in my project. It is really easy to work with.
Short Example:
const pdf = require('pdfkit');
const fs = require('fs');
const doc = new pdf();
doc.pipe(fs.createWriteStream('/my/path'));
doc.fontSize(10).text('Fontsize 10')
doc
.fontSize(18)
.text('Font Size 18 aligned right', {align: 'right'});
doc.moveDown();
doc.fontSize(14).text('Font size 14 aligned center',{align:'center' })
doc.end();

Aggregate function returns null GraphQL

I am testing a basic aggregation function using counts from Sequelize and here's my type Counts:
type Creserve {
id: ID!
rDateStart: Date!
rDateEnd: Date!
grade: Int!
section: String!
currentStatus: String!
user: User!
cartlab: Cartlab!
}
type Counts {
section: String!
count: Int
}
type Query {
getBooking(id: ID!): Creserve!
allBookings: [Creserve]
getBookingByUser(userId: ID): Creserve
upcomingBookings: [Creserve]
countBookings: [Counts]
}
I am using countBookings as my query for aggregate functions and here's my resolver for the query:
countBookings: async (parent, args, {models}) =>
{
const res = await models.Creserve.findAndCountAll({
group: 'section',
attributes: ['section', [Sequelize.fn('COUNT', 'section'), 'count']]
});
return res.rows;
},
The query that it outputs is this:
Executing (default): SELECT "section", COUNT('section') AS "count" FROM "Creserve" AS "Creserve" GROUP BY "section";
And tried this query in my psql shell and it's working fine:
section | count
---------+-------
A | 2
R | 2
However, when I tried querying countBookings in my GraphQL Playground, section is returned but not the count:
{
"data": {
"countBookings": [
{
"section": "A",
"count": null
},
{
"section": "R",
"count": null
}
]
}
}
Is there something I missed out? Or is this a bug? This is the answer I tried following to with this example: https://stackoverflow.com/a/45586121/9760036
Thank you very much!
edit: returning a console.log(res.rows) outputs something like this:
[ Creserve {
dataValues: { section: 'A', count: '2' },
_previousDataValues: { section: 'A', count: '2' },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: true,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
indexes: [],
name: [Object],
omitNull: false,
hooks: [Object],
sequelize: [Sequelize],
uniqueKeys: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [Array] },
__eagerlyLoadedAssociations: [],
isNewRecord: false },
Creserve {
dataValues: { section: 'R', count: '2' },
_previousDataValues: { section: 'R', count: '2' },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: true,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
indexes: [],
name: [Object],
omitNull: false,
hooks: [Object],
sequelize: [Sequelize],
uniqueKeys: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [Array] },
__eagerlyLoadedAssociations: [],
isNewRecord: false } ]
Here's for res.count:
Executing (default): SELECT "section", COUNT('section') AS "count" FROM "Creserve" AS "Creserve" GROUP BY "section";
[ { count: '2' }, { count: '2' } ]
Problem
Actually you are doing everything right here... but what is happening here is the sequlize doesn't return plain object... It always returns the data in form of instance like that
[ Creserve {
dataValues: { section: 'A', count: '2' },
_previousDataValues: { section: 'A', count: '2' },
_changed: {},
_modelOptions:
{ timestamps: true,
Solution
I am not sure but there is no other way instead of looping and makes
response to json object...
const array = []
res.rows.map((data) => {
array.push(data.toJSON())
})
return array

How does the Sequelize POJO JSON.stringify magic work?

In sequelize if you do a
db.MyTable.findAll({}).function(response){
console.log(response);
}
You will see output that looks like this (depending on what your table looks like, of course):
[ { dataValues:
{ id: 1,
text: 'sdf',
complete: false,
createdAt: Thu Jan 19 2017 11:55:38 GMT-0500 (Eastern Standard Time),
updatedAt: Thu Jan 19 2017 11:55:38 GMT-0500 (Eastern Standard Time) },
_previousDataValues:
{ id: 1,
text: 'sdf',
complete: false,
createdAt: Thu Jan 19 2017 11:55:38 GMT-0500 (Eastern Standard Time),
updatedAt: Thu Jan 19 2017 11:55:38 GMT-0500 (Eastern Standard Time) },
_changed: {},
'$modelOptions':
{ timestamps: true,
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: [],
name: [Object],
omitNul: false,
sequelize: [Object],
uniqueKeys: {},
hasPrimaryKeys: true },
'$options':
{ isNewRecord: false,
'$schema': null,
'$schemaDelimiter': '',
raw: true,
attributes: [Object] },
hasPrimaryKeys: true,
__eagerlyLoadedAssociations: [],
isNewRecord: false } ]
Suffice to say, it is a big complex object with a bunch of metaData on it.
However, if you try and turn that big complicated object into a string using either:
console.log(JSON.stringify(dbTodo));
or
res.json(dbTodo);
you will get back just the information for the actual entity (the items in the dataValues property of the big complex object). For my test table here, it looks like this:
[{
"id":1,
"text":"sdf",
"complete":false,
"createdAt":"2017-01-19T16:55:38.000Z",
"updatedAt":"2017-01-19T16:55:38.000Z"
}]
Which is significantly simpler (and just what I want).
How does this magic happen? Is sequelize creating their own versions of JSON.stringify() and express' res.json?
What are the rules around when it happens and when it doesn't happen?
I've searched through the sequelize docs and haven't found a good explanation.
There are two ways this behavior could manifest.
The missing properties are non-enumerable. Properties defined by Object.defineProperty set to enumerable: false (or simply don't supply a value for the enumerable setting) are non-enumerable properties, and are ignored by JSON.stringify. You can check a property's enumerable setting in the output of Object.getOwnPropertyDescriptor(obj, propName).
The object has (or has in its prototype chain) a toJSON method:
If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized.
If the object has or inherits a toJSON method, then the return value of that method will be the target for stringification. You can check if one exists on some object obj simply by reading the value of obj.toJSON.

Using Sequelize with ES6 Promises?

I'm using Sequelize to connect to a Postgres database. I have this code:
return Promise.resolve()
.then(() => {
console.log('checkpoint #1');
const temp = connectors.IM.create(args);
return temp;
})
.then((x) => console.log(x))
.then((args) =>{
console.log(args);
args = Array.from(args);
console.log('checkpoint #2');
const temp = connectors.IM.findAll({ where: args }).then((res) => res.map((item) => item.dataValues))
return temp;
}
)
.then(comment => {
return comment;
})
.catch((err)=>{console.log(err);});
In the first .then block at checkpoint #1, the new record is successfully added to the Postgres database. In the console.log(x) in the next then block, this gets logged to the console:
{ dataValues:
{ id: 21,
fromID: '1',
toID: '2',
msgText: 'Test from GraphIQL',
updatedAt: Wed Oct 12 2016 09:52:05 GMT-0700 (PDT),
createdAt: Wed Oct 12 2016 09:52:05 GMT-0700 (PDT) },
_previousDataValues:
{ fromID: '1',
toID: '2',
msgText: 'Test from GraphIQL',
id: 21,
createdAt: Wed Oct 12 2016 09:52:05 GMT-0700 (PDT),
updatedAt: Wed Oct 12 2016 09:52:05 GMT-0700 (PDT) },
_changed:
{ fromID: false,
toID: false,
msgText: false,
id: false,
createdAt: false,
updatedAt: false },
'$modelOptions':
{ timestamps: true,
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: [],
name: { plural: 'IMs', singular: 'IM' },
omitNul: false,
sequelize:
{ options: [Object],
config: [Object],
dialect: [Object],
models: [Object],
modelManager: [Object],
connectionManager: [Object],
importCache: {},
test: [Object],
queryInterface: [Object] },
uniqueKeys: {},
hasPrimaryKeys: true },
'$options':
{ isNewRecord: true,
'$schema': null,
'$schemaDelimiter': '',
attributes: undefined,
include: undefined,
raw: undefined,
silent: undefined },
hasPrimaryKeys: true,
__eagerlyLoadedAssociations: [],
isNewRecord: false }
In the .then((args) => code block at checkpoint #2, args comes in as undefined.
How do I get args to contain an array of results from checkpoint #1?
.then((x) => console.log(x))
.then((args) =>{
is like doing
.then((x) => {
console.log(x);
return undefined;
})
.then((args) =>{
because console.log returns undefined. That means the undefined value will be what gets passed to the next .then.
The easiest approach would be to explicitly
.then((x) => {
console.log(x);
return x;
})
or in a shorter version using the comma operator
.then((x) => (console.log(x), x))

Resources