NodeJs server side is not starting due of function import - node.js

Firs time I faced with such issue, I have (the working case):
const weekendsInMonth = (anydate) => {
let today_tmp = new Date();
let today = new Date(today_tmp.getTime() - today_tmp.getTimezoneOffset()*60*1000);
let lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0).getDate();
let myDate = today;
//some other function code
Once I do modification to function (only anydate IN variable, second row):
const weekendsInMonth = (anydate) => {
let today_tmp = new Date(anydate);
let today = new Date(today_tmp.getTime() - today_tmp.getTimezoneOffset()*60*1000);
let lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0).getDate();
let myDate = today;
//some other function code
The NodeJs says only:
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
And nothing happens, actually there is more rows in output should come, like web server started at port, etc. No warnings, no erros and app page could not be viewev in browser (only error - ERR_CONNECTION_REFUSED). What am I doing wrong?
I am importing this function to my server.js as:
const {daysInThisMonth, weekendsInMonth, } = require("./src/core/functions");
Same time the other similar function does not fault:
const daysInThisMonth = (date) => {
var now = new Date(date);
return new Date(now.getFullYear(), now.getMonth()+1, 0).getDate();
}

I figured out it. The problem was that date must be defined in this case:
const weekendsInMonth = (anydate = new Date) => {
let today_tmp = new Date();
let today = new Date(today_tmp.getTime() - today_tmp.getTimezoneOffset()*60*1000);
let lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0).getDate();
let myDate = today;
//some other function code
For me this case was a surprise. Due this function only calling inside another function in a special circumstance. After I did a debug and this function is asking for date to be defined first.

Related

can not get cascade DDS value for SharedObjectSequence

I have a test like this, but i can not get the 'sharedMap' in 'sharedSeq1' value, i don't know how to get the 'remoteFluidObjectHandle' value.
import {MockContainerRuntimeFactory, MockFluidDataStoreRuntime, MockStorage} from "#fluidframework/test-runtime-utils";
import {SharedObjectSequence, SharedObjectSequenceFactory} from "#fluidframework/sequence";
import * as mocks from "#fluidframework/test-runtime-utils";
import {SharedMap} from "#fluidframework/map";
import {IFluidHandle} from "#fluidframework/core-interfaces";
const mockRuntime: mocks.MockFluidDataStoreRuntime = new mocks.MockFluidDataStoreRuntime();
describe('ShredObjectSequence', function () {
it('should get synchronization data from another shared object', async function () {
const dataStoreRuntime1 = new MockFluidDataStoreRuntime();
const sharedSeq1: SharedObjectSequence<IFluidHandle<SharedMap>> = new SharedObjectSequence(mockRuntime, 'shareObjectSeq1', SharedObjectSequenceFactory.Attributes,)
const containerRuntimeFactory = new MockContainerRuntimeFactory();
dataStoreRuntime1.local = false;
const containerRuntime1 = containerRuntimeFactory.createContainerRuntime(
dataStoreRuntime1,
);
const services1 = {
deltaConnection: containerRuntime1.createDeltaConnection(),
objectStorage: new MockStorage(),
};
sharedSeq1.initializeLocal();
sharedSeq1.connect(services1);
const dataStoreRuntime2 = new MockFluidDataStoreRuntime();
const containerRuntime2 = containerRuntimeFactory.createContainerRuntime(
dataStoreRuntime2,
);
const services2 = {
deltaConnection: containerRuntime2.createDeltaConnection(),
objectStorage: new MockStorage(),
};
const sharedSeq2: SharedObjectSequence<IFluidHandle<SharedMap>> = new SharedObjectSequence(mockRuntime, 'shareObjectSeq2', SharedObjectSequenceFactory.Attributes,)
sharedSeq2.initializeLocal();
sharedSeq2.connect(services2);
// insert a node into sharedSeq2, it will sync to sharedSeq1
sharedSeq2.insert(0, [<IFluidHandle<SharedMap>>new SharedMap('sharedMapId', mockRuntime, SharedMap.getFactory().attributes).handle])
containerRuntimeFactory.processAllMessages();
// next case is passed, it show we got the sharedSeq2 changed
expect(sharedSeq1.getLength()).toBe(1)
const remoteFluidObjectHandle = await sharedSeq1.getRange(0, 1)[0];
// at here, i get error: Cannot read property 'mimeType' of null, it cause by remoteFluidObjectHandle.ts:51:30
const sharedMap = await remoteFluidObjectHandle.get()
expect(sharedMap).not.toBeUndefined()
});
});
run this test will get 'Cannot read property 'mimeType' of null' error, it caused by 'remoteFluidObjectHandle.ts:51:30'
The fluid mocks have very limited and specific behaviors, it looks like you are hitting the limits of them. You'll have better luck with an end-to-end test, see packages\test\end-to-end-tests. These use the same in-memory server as our as the playground on fluidframework dot com. The in-memory server uses the same code as tinylicious, our single process server and routerlicious, our docker based reference implementation.

Gremlin Javascript order by function

I use gremlin-javascript (in aws Neptune) to traverse the remote graph and get a list of vertex. I want order the vertex by their createdAt date property. But since I have multiple order().by(), I want to group them by week.
const gremlin = require('gremlin')
const moment = require('moment')
const { Graph } = gremlin.structure
const { DriverRemoteConnection } = gremlin.driver
const __ = gremlin.process.statics
const { order } = gremlin.process
const getWeek = date => parseInt(moment(date).format('YYYYWW'), 10)
const graph = new Graph()
const dc = new DriverRemoteConnection(endpointNeptune)
const g = graph.traversal().withRemote(dc)
g.V().order().by(getWeek(__.values('createdAt')), order.decr)
But this throw an error: "Could not locate method: NeptuneGraphTraversal.by([202029, decr])"
Thank you in advance
Copying my earlier comment to an answer:
The by modulator is expecting a key name not a literal value. Something like
g.V().group().by('createdAt').order(local).by(keys,desc)
or perhaps depending on your data model
g.V().order().by('createdAt', order.desc)

Difference between two dates including the first and last day in JS

i have two dates, where the first one is the date start and the second one is the date end.
I have to translate this in number of Years, Months and Days.
Example:
const start = moment(new Date('2021-03-03'))
const end = moment(new Date('2022-03-03'))
const difference = moment.duration(end.diff(start))
const days = difference.days() //30
const months = difference.months() // 11
const years = difference.years() // 0
the result is:
{"days":30,"months":11,"years":0}
But my expected behavior is:
{"days":0,"months":0,"years":1}
How can I reach this?
To achieve your expected behavior just simply change your code:
from this:
const end = moment(new Date('2022-03-03'))
to this:
const end = moment(new Date('2022-03-03')).add('1', 'days')
This will give: {"days":0,"months":0,"years":1}
Final full updated code:
const start = moment(new Date('2021-03-03'))
const end = moment(new Date('2022-03-03')).add('1', 'days')
const difference = moment.duration(end.diff(start))
const days = difference.days() // 0
const months = difference.months() // 0
const years = difference.years() // 1
I think it is because at 03/03 it will always remain at least a millisecond to complete the year.
For example i try to use .startOf('d') and .endOf('d') and this is the results:
const start = moment(new Date('2021-03-03')).startOf('d')
const end = moment(new Date('2022-03-03')).endOf('d')
moment("2021-03-03T00:00:00.000")
moment("2022-03-03T23:59:59.999")
Alex.

How to pass a variable from one module to another?

I know there may be a duplicate question but I've been reading and really struggling to understand and figure out how to pass a variable from a command module into an event module shown below.
Command:
exports.run = async (client, message, args) => {
const embed = new Discord.RichEmbed()
.addField(':heart:', `${xb.toString()}`, true)
.addField(':black_heart:', `${ps.toString()}`, true)
.addField(':yellow_heart:', `${nin.toString()}`, true)
.addField(':purple_heart:', `${pcmr.toString()}`, true)
message.channel.send(embed).then(async msg => {
let embedid = msg.id;
module.exports.embedid = embedid;
await msg.react('❤');
await msg.react('🖤');
await msg.react('💛');
await msg.react('💜');
});
}
Event:
module.exports = async (client, messageReaction, user) => {
const message = messageReaction.message;
const channel = message.guild.channels.find(c => c.name === 'role-assignment');
const member = message.guild.members.get(user.id);
if(member.user.bot) return;
const xb = message.guild.roles.get('540281375106924555');
const ps = message.guild.roles.get('540296583632388115');
const nin = message.guild.roles.get('540296630260203520');
const pcmr = message.guild.roles.get('540296669733060618');
if(['❤', '🖤', '💛', '💜'].includes(messageReaction.emoji.name) && message.channel.id === channel.id && messageReaction.message.id === embedid) {};
I'm hoping to pass embedid, embed2id and so on to the event module so I can filter by the message ID that is generated when sending the RichEmbed()
Thanks in advance, I've been running in circles for days!
So I figured it out by looking into what exports actually do, which really, should have been the first thing I did, here :
What is the purpose of Node.js module.exports and how do you use it?
Using the info learned here, I made the following changes to my event:
const e1 = require('../commands/startroles'); // At the top of my messageReactionAdd.js file before module.exports[...]
messageReaction.message.id === e1.embedid // added the e1. to import the variable.

Get new object from another class nodejs

Ok so I have a class that contains
Object JS
var GameServer = require("./GameServer");
var gameServer = new GameServer();
GameServer() contains
GameServer JS
function GameServer() {
// Startup
this.run = true;
this.lastNodeId = 1;
this.lastPlayerId = 1;
this.clients = [];
this.largestClient; // Required for spectators
this.nodes = [];
this.nodesVirus = []; // Virus nodes
this.nodesEjected = []; // Ejected mass nodes
this.nodesPlayer = []; // Nodes controlled by players
}
Now, what im trying to acheive is getting gameServer from ObjectClass
In my class i've tried
new JS
var ObjectClass = require("./ObjectClass");
var gameServer = ObjectClass.gameServer;
But from this way, I won't be able to grab the class GameServer() properties. I'm new to node and im sorry I have to ask this question. I'm currently stuck right now
When I try to grab clients from GameServer
var ObjectClass = require("./ObjectClass");
var gameServer = ObjectClass.gameServer;
gameServer.clients.length;
I get error, clients is undefined. Any way around this?.
I cannot modify GameServer nor Object js.. Basicly im making a script attacthed to a script for extra functionalities.
You are missing the exports of your files so when doing require(file) you're getting and empty object {}..
For gameServer you should be doing something like:
'use strict';
function GameServer() {
// Startup
this.run = true;
this.lastNodeId = 1;
this.lastPlayerId = 1;
this.clients = [];
this.largestClient; // Required for spectators
this.nodes = [];
this.nodesVirus = []; // Virus nodes
this.nodesEjected = []; // Ejected mass nodes
this.nodesPlayer = []; // Nodes controlled by players
}
module.exports = exports = GameServer;
ObjectClass
'use strict';
var GameServer = require("./GameServer");
var gameServer = new GameServer();
exports.gameServer = gameServer;
You need to understand that require cache the value returned by the file, so you would be using a singleton of gameServer.

Resources