how to create two class at a js page in node js? - node.js

class tasit {
constructor(cins) {
this.cins = cins;
}
}
class araba extends tasit {
constructor(cins, renk, hiz) {
super(cins);
this.renk = renk;
this.hiz = hiz;
}
}
module.exports = {tasit, araba};
I want to create 2 classes in a .js file and I want to export them. How do I export or do I can export classes?
module.exports = {tasit, araba};
here is error message.
ReferenceError: araba is not defined

Your export is just fine. This is one way to import your classes:
// Assuming you've created your classes in myclasses.js
const {Araba, Tasit} = require('./myclasses.js')
myAraba = new Araba(1, 'a', true)
myTasit = new Tasit(10)
console.log(myAraba.hiz, myAraba.renk, myAraba.cins)
console.log(myTasit.cins)
outputs
true 'a' 1
10
Only note that I capitalized your class names.

Related

How to determine if "click" or "box-select" was used with Streamlit/Plotly to return data from chart to Streamlit

I'm not a Javascript/Typescript/React dev. I'm hacking my way through this for a work project.
I'm using Streamlit, with plotly.
I'm hacking the basic code from streamlit-plotly-events.
I was trying to have the click or box-select information passed back with the data selected via the plotlyEventHandler() (see code below.) However, both this.props.args["click_event"] and this.props.args["select_event"] are true, regardless of whether you use box-select in the plotly chart, or click a single data point in the chart.
I thought of assuming if there is only one data point, then it was a click - but you can box select only one data point.
// import React, {useState,useEffect} from "react"
import React, { ReactNode } from "react"
//import React from "react"
import {
StreamlitComponentBase,
withStreamlitConnection,
Streamlit,
// ComponentProps,
} from "streamlit-component-lib"
import Plot from "react-plotly.js"
class StreamlitPlotlyEventsCapture extends StreamlitComponentBase {
public render = (): ReactNode => {
// Pull Plotly object from args and parse
const plot_obj = JSON.parse(this.props.args["plot_obj"]);
const override_height = this.props.args["override_height"];
const override_width = this.props.args["override_width"];
// Event booleans
const click_event = this.props.args["click_event"];
const select_event = this.props.args["select_event"];
const hover_event = this.props.args["hover_event"];
Streamlit.setFrameHeight(override_height);
return (
<Plot
data={plot_obj.data}
layout={plot_obj.layout}
config={plot_obj.config}
frames={plot_obj.frames}
onClick={click_event ? this.plotlyEventHandler : function(){}}
onSelected={select_event ? this.plotlyEventHandler : function(){}}
onHover={hover_event ? this.plotlyEventHandler : function(){}}
style={{width: override_width, height: override_height}}
className="stPlotlyChart"
/>
)
}
/** Click handler for plot. */
private plotlyEventHandler = (data: any) => {
// Build array of points to return
var clickedPoints: Array<any> = [];
//const util = require('util')//#33333 used with util.inspect(arrayItem) below
// I dont know why we can't directly use "this.variables" in the clickedPoints.push
// but we can't, so we create the variables here.
var wasClicked = this.props.args["click_event"];
var wasSelected = this.props.args["select_event"];
var wasHovered = this.props.args["hover_event"];
data.points.forEach(function (arrayItem: any) {
// console.log(util.inspect(arrayItem, {maxArrayLength: null, depth:null }))
clickedPoints.push({
// I dont know why we can't directly use "this.variables" here, but we can't
// so we use the variables created above.
clicked:wasClicked,
selected:wasSelected,
hovered:wasHovered,
x: arrayItem.x,
y: arrayItem.y,
curveNumber: arrayItem.curveNumber,
pointNumber: arrayItem.pointNumber,
pointIndex: arrayItem.pointIndex
})
});
// Return array as JSON to Streamlit
Streamlit.setComponentValue(JSON.stringify(clickedPoints))
}
}
export default withStreamlitConnection(StreamlitPlotlyEventsCapture)

AWS-CDK: Need to pass resource generated in pipeline to a created stack

I'm currently working on a cross-account deployment pipeline.
I'm using 4 different stacks:
BackendPipelineStack
CommonInfrastructureStack
AssetDeploymentStack
BusinessAssetAPIStack
The last 2 stacks both have props that include a generated Layer and built JS files (for the different Lambdas).
My cdk.ts looks like this:
import * as cdk from "#aws-cdk/core"
import { BackendPipelineStack } from "../lib/backend-pipeline"
import { BusinessAssetAPIStack } from "../lib/business-asset-api-stack"
import { projectConfig } from "../config/config"
import { AssetDeploymentStack } from "../lib/asset-deployment-stack"
import { CommonInfrastructureStack } from "../lib/common-infrastructure-stack"
const app = new cdk.App()
const commonInfraStack = new CommonInfrastructureStack(app, "CommonInfrastructureStack", {
stackName: `${projectConfig.resourcePrefix}-common-infrastructure-stack`,
})
const apiStack = new BusinessAssetAPIStack(app, "BusinessAssetAPIStack", {
stackName: `${projectConfig.resourcePrefix}-business-asset-api-stack`,
...,
installationUserEmailIndexName: commonInfraStack.installationTechnicalAssetUserEmailIndexName,
})
const deploymentStack = new AssetDeploymentStack(app, "AssetDeploymentStack", {
stackName: `${projectConfig.resourcePrefix}-asset-deployment-stack`,
...,
installationAccountRegionIndexName: commonInfraStack.installationAccountRegionIndexName,
})
new BackendPipelineStack(app, "BackendPipelineStack", {
nonProdAccountId: "nonProdAccountId",
apiStack,
commonInfraStack,
deploymentStack,
})
My BackendPipelineStack stack is the one generating the codepipeline.Artifacts that store both the built JS files and Layers.
//backend-pipeline.ts
export class BackendPipelineStack extends Stack {
...
const lambdaBuildOutput = new Artifact("DistArtifact")
const lambdaLayer = new Artifact("LayerArtifact")
...
I want to be able to pass both Artifacts to the other stacks that are passed thru the PipelineStack constructor.
Is there anyway to do this?
I found the answer for those who would be stuck in the same situation as I was.
Looking into pipeline actions, there is one called CloudFormationCreateOrUpdateStack that allows to override parameters provided in the Lambda Stack thru CfnParametersCode (here's a python example).

How do I test a function that is in a class with Jest

I have a function that is in a class :
Simplified version :
export class Button {
getAttributes(el) {
//random code that was removed for simplicity
return dataAttrs;
}
}
I was wondering how do I test this in Jest.
Here is what worked for me :
test('get attributes on element', () => {
let button= new Button();
var element = document.createElement('a');
element.setAttribute('href', 'https://www.google.ca/');
element.innerHTML = 'Test';
expect(breadcrumb.getAttributes(element)).toBe('Hello');
});
if there is simple class like the one that u define u can do:
it('We can check the class constructor', () => {
const classObject = new classObject();
expect(classObject ).toHaveBeenCalledTimes(1);
});
and use whatever the methods that Jest have.
But if there are complex classes and methods that ones are dependent from others i suggest you to read this and you can automatize it or can do it manually, mock the dependences and test it out.

How to work around the require(“../../../../../../../”) frustration In NodeJS?

Any better ways of solving this kind of problem in node.js below?
import foo from "../../../modules/home/models/index.js"
import bar from "../../../modules/about/models/index.js"
import baz from "../../../modules/contact/models/index.js"
At least making them into something like this?
import foo from "/home/models/index.js"
import bar from "/about/models/index.js"
import baz from "/contact/models/index.js"
Any ideas?
You need inversion of control.
./modules/home/index.js
const homeModel1 = () => {
//...
}
const homeModel2 = () => {
//...
}
module.exports = Object.assign({}, { homeModel1, homeModel2 })
1. An object will be exported of the following shape:
{
homeModel1: () => {},
homeModel2: () => {}
}
2. When you add a new model, simply add it or import it into this file and then add it to the export object.
./modules/index.js
import { homeModels } from './modules/home'
import { aboutModels } from './modules/about'
import { contactModels } from './modules/contact'
module.exports = Object.assign({}, { homeModels, aboutModels, contactModels })
The models are destructured out and then exported as methods on a new object.
Likewise, same shape object is exported with all your models cultivated together, bringing all their dependencies with them.
somewhere else
import modules from './modules'
const query = modules.homeModels.homeModel1()
Bonus:
To clarify, Object.assign({}, obj1, obj2) creates a new object with the prototype set to the Object prototype, and merges the properties and methods of obj1 and obj2. In this simple form, it is essentially the same as const obj = {}.
A bit more advanced, is Object.assign({}, { obj1, obj2 }) which makes obj1 and obj2 properties on the new object. You can do some simple testing to get a feel for the data structures.
We also used some destructuring. If you are having issues getting things lined up properly, you should look at those aspects plus how you are importing them into a file. For example, import obj1 from './modules' will bring the entire object in from ./modules, but import { obj1 } from './modules' will destructure obj1 from the object that it pulls in, so obj1 was a method/property of the object.
Do some research into inversion of control and dependency injection.

Export class and instanciate it immediately on import

I have a ES6 class in NodeJS 4 :
vehicule.js
"use strict";
class Vehicule {
constructor(color) {
this.color = color;
}
}
module.exports = Vehicule;
When I need to instanciate in another file, I find myself doing this :
var _Vehicule = require("./vehicule.js");
var Vehicule = new _Vehicule();
I'm new to nodeJs, is there a way to do this in one line, or at least in a more readable way ?
A class is really supposed to be reused for many objects. So you should require the class itself:
var Vehicule = require("./vehicule.js");
and then create objects from it:
var vehicle1 = new Vehicule('some data here');
var vehicle2 = new Vehicule('other data here');
Usually classes start with an upper case letter, and instances of classes (objects themselves) with a lower case one.
If you want a "class" for just one objects, you can just create an inline object:
var vehicle = {
myProperty: 'something'
};
module.exports = vehicle;
//in some other file
var vehicle = require('vehicle');
Though if you really, really want to do that in one line, you can do:
var vehicle = new (require('vehicle'))('some constructor data here');
But that is not recommended. Pretty much ever.
If you really want to do this in one line:
var Vehicule = new (require('./vehicule'))('red');
but personally i would prefer two lines for the same reasons mentioned by #ralh.

Resources