How to disconnec the db connection in node js
Category: javascript
Category Added in a WPeMatico Campaign
Get arguments from withing a script html tag given by the api
This topic has been discussed a lot but here is my problem.
I receive from my api an object containing a script
[
{
"script": "<script src=xxx.js></script>",
"onScriptHead": true,
"onScriptOnLoad": false,
},
{
"script": "<script type="application/javascript">do something else</script>",
"onScriptHead": true,
"onScriptOnLoad": false,
}
]
Now my aim is to inject those script based on onScriptHead / onScriptLoad value.
I managed to create a code that can push a script on the head but only if there are no args inside the script tag
here is the code mentionned above
export const createScript = (scriptToInject: string, scriptSettings?: scriptSettingsProps) => {
const { onScriptHead } = scriptSettings ?? {};
const regexHTMLTag = /<([a-z]+)>/gi;
const inverseScriptRegex = /<[^>]*script/gi;
const addScriptTagToDom = (
retrieveScriptData: RegExpExecArray | string | null,
scriptTag?: any
) => {
const newScript = scriptTag
? document.createElement(`${scriptTag}`)
: document.createElement('script');
if (Array.isArray(retrieveScriptData)) {
const [, scriptData] = retrieveScriptData;
newScript.innerHTML = scriptData;
} else if (typeof retrieveScriptData === 'string') {
newScript.innerHTML = retrieveScriptData;
}
document.head.append(newScript);
};
let match = regexHTMLTag.exec(scriptToInject);
while (match !== null) {
const scriptTag = match[1];
const scriptRegex = new RegExp(`<${scriptTag}[^>]*>([\s\S]*?)</${scriptTag}>`);
const finalScript = scriptRegex.exec(scriptToInject) ? scriptRegex.exec(scriptToInject) : '';
if (onScriptHead) {
addScriptTagToDom(finalScript, scriptTag);
}
match = regexHTMLTag.exec(scriptToInject);
}
};
I cannot find a way to get the script, strip it down, then remount it using js document.xxx to use it in my dom
I have tried multiple regex and online solutions, but cannot find a dynamic way to inject my script after getting it from my api
useState value does not change
In setInterval, I’m trying to add constantly changing data to the useState hook, but it always shows the first value.
I don’t want to use spread operator or prev constructs (it works with these), because the data will be updated every 1 second. Since these structures constantly copy data to memory, memory usage constantly increases.
Is there any other method to update the useState value continuously.
example code;
const [getData, setData] = useState(data);
const exData = [] // Constantly Updating
useEffect(() => {
const interval = setInterval(() => {
setData(exData);
}, 1000);
return () => clearInterval(interval);
}, []);
useEffect(() => {
console.log(getData);
}, [getData]);
Logic behind how Next.js builds dynamic pages using the app router system?
Background: dynamic
pages
I have some large pages in my Next.js app currently (app router style), and am trying to debug why the pages are so large, and it’s hard to say the least.
Route (app) Size First Load JS
┌ ○ / 3.29 kB 846 kB
├ ○ /_not-found 142 B 86.5 kB
├ ○ /my/first/page 1.56 kB 414 kB
├ λ /my/dynamic/page/[x] 57.8 kB 636 kB
├ λ /my/other/page 326 kB 1.32 MB
...
+ First Load JS shared by all 86.3 kB
├ chunks/4422-2c92fefc06002e18.js 30.3 kB
├ chunks/65b6c8ea-4ad97acde17233b9.js 53.6 kB
└ other shared chunks (total) 2.38 kB
One of my pages, the /my/dynamic/page/[x]
, has this in it:
import dynamic from 'next/dynamic'
const ACTUAL_PAGE = {
a: dynamic(() => import("~/components/page/A")),
b: dynamic(() => import("~/components/page/B")),
c: dynamic(() => import("~/components/page/C")),
d: dynamic(() => import("~/components/page/D")),
// .. up to t, 20 different styles of pages, under the same URL.
};
export default function Page({ params }) {
const ActualPage = ACTUAL_PAGE[params.x]
return <ActualPage />
}
Sidenote: URL structure
I need this because I have these routes:
/convert/ttf/otf
/convert/png/jpg
/convert/rgb/hex
/convert/other/stuff
So I have a FontConverter
page, ImageConverter
, etc., 20 different types of converters, using the same URL system. I could do this:
/convert/font/ttf/otf
/convert/image/png/jpg
/convert/color/rgb/hex
/convert/some/other/stuff
But I don’t want to do that… I like the simplicity of the URL structure I have.
Observation: dynamic
subpages add to build size
When I comment out all but 1 ACTUAL_PAGE
from above, it goes down to 400kb (still have more to figure out why my pages are so large). Each page I comment back in, it goes up by roughly 80kb:
- 1 page: 400kb
- 2 pages: 480kb
- 3 pages: 560kb
- 4 pages: 640kb
Assumption: dynamic
pages aren’t included in the build?
I assumed that all my dynamic
pages weren’t included in the build? But obviously they are somehow… Because commenting one in at a time slowly increases the final First Load JS
in the top λ /my/dynamic/page/[x]
log.
Question
How does dynamic
work with the output bundles? How does it change First Load JS
? Also, what exactly is the difference between Size
and First Load JS
? (I haven’t seen that in the docs yet).
I noticed that using const Component = await import("~/components/page/A");
in a switch statement, like:
switch (params.x) {
case "a": {
const Component = (await import("~/components/page/A")).default;
return <Component />;
}
case "b": {
const Component = (await import("~/components/page/B")).default;
return <Component />;
}
// ...
}
Also resulted in the same behavior, of First Load JS
incrementing every page I added. So somehow the build/bundle is including my sub-imports intelligently.
How does it work?
Send a confirmation email after the sign up, after that put that data in the database [closed]
I’m pretty new to php.
I have a sign up form with username, email and password, when the user clicks sign up I want to send an email for confirmation, and after that send the data to the database, i want to avoid using storing the password in a session variable
I can do these things separately, but i don’t know how to use them all together
Possibility of changing userId from oneSignal ” Android “
I’m working on an Android application that utilizes OneSignal for push notifications. I’ve encountered a scenario where I need to change the userId associated with the OneSignal player. However, I couldn’t find a clear way to achieve this in the OneSignal documentation.
Is there a recommended approach or method provided by OneSignal or any workarounds to change the userId programmatically within an Android application? Any insights or code examples would be greatly appreciated.
Next.js 14 Draft Mode not working in an iframe(headless CMS preview)
I have tried using the Draft Mode in two of my projects which are built with combination of Next.js 14 and Headless CMS(Storyblok, Crystalize). While the Draft Mode workes perfectly fine in a browser tab it doesn’t work in any of the the CMS UI’s preview(iframe). I have previous projects built with the pages router and the “Preview Mode”(same functionality as draft mode) in them works so it’s nothing to do with the CMS’s.
Here’s my setup:
- Next.js 14.0.4
- local-ssl-proxy(the iframes require https)
- Chrome v121
- CMS: Storyblok or Crystalize
- Ubuntu 22.04.3
Here’s my draft/route.ts
:
// route handler with secret and slug
import { draftMode } from 'next/headers';
import { redirect } from 'next/navigation';
import { paths } from '@/constants/paths';
export async function GET(request: Request) {
// Parse query string parameters
const { searchParams } = new URL(request.url);
const crystallizeSignature = searchParams.get('crystallizeSignature');
const slug = searchParams.get('slug');
// TODO: Check the secret and slug
if (!crystallizeSignature || !slug) {
return new Response('Invalid token', { status: 401 });
}
// Enable Draft Mode by setting the cookie
draftMode().enable();
// Redirect to the path from the fetched post and remove the prefix
const slugWithoutPrefix = slug.replace(paths.crystallizeRoot, '');
redirect(`${slugWithoutPrefix}`);
}
Here’s what i tried and didn’t work:
- Updating Nextjs to latest version
- Refered to this GH issue. I have tried all the solutions/workarounds people suggested but none of them worked. Even checking if the cookie was correct in the response:
- Using Firefox
- Setting a random cookie(e.g test-cookie=123455) to check if any cookie will be set at all and when i logged out all cookies the test-cookie was visible in the iframe
Creating an Organization in Github Enterprise with the REST API
I am trying to automate the configuration of a Github Enterprise. This ofcourse starts with the organizations. Github has a REST API for this.
Whenever I run the script with secrets.GITHUB_TOKEN I get the error: “Resource not accessible by integration”. 403
If I run the script with a fine grained pat with full permissions I get the error: “Not Found” 404
I am running this script from in a repository in an organization in the Enterprise where I am trying to make a new organization. Code below.
name: Config Enterprise
permissions:
write-all
on:
push:
branches:
- main
jobs:
my-action:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm install @octokit/action
- run: node .github/actions/createORG.js
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN}}
const { Octokit } = require("@octokit/core");
const octokit = new Octokit({
authorization: `token ${process.env.GITHUB_TOKEN}`
})
async function createORG(orgUserName, orgDisplayName, admin) {
try {
await octokit.request('POST /admin/organizations', {
login: orgUserName,
profile_name: orgDisplayName,
admin: admin,
headers: {
authorization: `token ${process.env.GITHUB_TOKEN}`,
'X-GitHub-Api-Version': '2022-11-28'
}
});
console.log("Created organization");
} catch (error) {
console.error("Error:", error);
}
}
createORG('DLW-TEST2-EMRE', 'DLW-TEST2-EMRE', 'igtene_dlwr')
Getting Module ‘”react-router-dom”‘ has no exported member ‘RouteComponentProps error when migrating to react-router v6
We are having legacy class based code for which we are trying to migrate to latest react router that is version 6. During migration we are getting this error, Module '"react-router-dom"' has no exported member 'RouteComponentProps
. We have added withRouter
wrapper to add the legacy support.
import { useLocation, useNavigate, useParams } from "react-router-dom";
function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return <Component {...props} router={{ location, navigate, params }} />;
}
return ComponentWithRouterProp;
}
export default withRouter;
Our class based component looks like this,
import { Route, RouteComponentProps, Routes } from "react-router-dom";
class App extends React.Component<{} & RouteComponentProps<{}>, IState> {
constructor(props: RouteComponentProps<{}>) {
super(props);
this.state = {
prop1: null
};
}
componentDidMount() {
if (this.props.location.pathname === "/test") {
window.location.reload();
}
};
render() {
return (
<Routes>
<Route path="/test" element={<Test />} />
</Routes>
)
}
}
export default withRouter(App);
How do I fix this issue?
Error: Module build failed (from ./node_modules/vue-loader/dist/index.js)
I’m setting up a laravel project and see an error as below. I have no clue as to what the cause is. Please help identify a fix
ncaught Error: Module build failed (from ./node_modules/vue-loader/dist/index.js):
TypeError: Cannot read properties of undefined (reading 'styles')
at Object.loader (D:Projectsamazing-ads-toolnode_modulesvue-loaderdistindex.js:96:34)
at ./resources/js/components/AmzSkuSearchComponent.vue (app.js?id=1015a1c7a0a1d02c4d096e84f60ab811:132:7)
at __webpack_require__ (app.js?id=1015a1c7a0a1d02c4d096e84f60ab811:232:42)
at webpackContext (app.js?id=1015a1c7a0a1d02c4d096e84f60ab811:182:9)
at eval (app.js:20:75)
at Array.map (<anonymous>)
at eval (app.js:20:14)
at ./resources/js/app.js (app.js?id=1015a1c7a0a1d02c4d096e84f60ab811:18:1)
at __webpack_require__ (app.js?id=1015a1c7a0a1d02c4d096e84f60ab811:232:42)
at app.js?id=1015a1c7a0a1d02c4d096e84f60ab811:385:64
at __webpack_require__.O (app.js?id=1015a1c7a0a1d02c4d096e84f60ab811:269:23)
I followed several of the SO posts
How to upgrade AWS EC2 instance type t2.medium to t3.medium?
I want to upgrade intance type T2.Medium to T3.Medium and follow the these steps.
- Stop the instance.
- Go to Instance Settings > Change Instance Type > t3.medium > Save.
- then try to start the Instance again.
But it’s given me this type of error message –
**Failed to start the instance --instance-id--
Enhanced networking with the Elastic Network Adapter (ENA) is required for the 't3.medium' instance type. Ensure that your instance '--instance-id--' is enabled for ENA.**
**Failed to start the instance --instance-id--
Enhanced networking with the Elastic Network Adapter (ENA) is required for the 't3.medium' instance type. Ensure that your instance '--instance-id--' is enabled for ENA.**
How to fix this issue without losing any data?
Is S3 deleteObjects API synchronous?
I am developing one solution to delete multiple files from S3 at once. While doing so I encountered a S3 api that deleted multiple objects at the same time.
I have used promises to handle this operation as S3 returns callback.
return new Promise((resolve, reject) => {
s3.deleteObjects({
Bucket: 'my-bucket',
Delete: {
Objects: keys
}
}, (err, data) => {
if (err)
return reject(err)
console.log(data)
return resolve(data)
});
});
}
This API returns all keys that have been deleted. However, when I went through some of the stack-overflow questions, it appears that this API might take some time to delete files physically.
But this is not the case every time. Somtimes it takes several milliseconds, minutes or hours.
Is this expected behavior of the API? If not is it synhronous or asynchronous.
PS: By sync/ async I mean file deletion operation and not the response of the API.
How Highlight IFC Model in Three.js with Raycasting
I want to create a IFC Loader with Three.js and i loaded the IFC file in the scene using Web-IFC-Three but how can i highlight the ifc model on mouse hover and get attributed of that part with three.js
i have tried using raycast in three.js but getting some error when try to highlight that model
How to implement search in the array of object using javascript
Need to implement the search the value includes or not in the array of object, if exists only filter the particular object to display. Here is my solution
let data = [
{
"name": "Human Capital Management (HCM)",
"description": "data entry with automatic data syncing capabilities.",
"listingType": "integration",
"connectors": [
{
"name": "oracle",
"description": "our global platform",
"companyName": "Oracle",
},
{
"name": "greenhouse",
"description": "our global platform",
"companyName": "greenhouse",
}
]
},
{
"name": "Applicant tracking system (ATS)",
"description": "data entry with automatic data syncing capabilities.",
"listingType": "integration",
"connectors": [
{
"name": "HiBob",
"description": "our global platform",
"companyName": "HiBob",
},
{
"name": "greenhouse",
"description": "our global platform",
"companyName": "greenhouse",
}
]
},
]
Search value is
let searchVal = 'Greenhouse'
filtering function
let responseData = []
await Promise.all(data.map(async (value)=> {
if(value.name.includes(searchVal)) {
responseData.push(value)
}
if(value.listingType.includes(searchVal)) {
responseData.push(value)
}
if(Array.isArray(value.connectors)) {
let connectors = await filterConnection(value.connectors, searchVal)
if(Array.isArray(connectors) && connectors.length > 0) {
responseData.push({
...value,
connectors
})
}
}
}))
return responseData
Need to implement the search function with more efficient code, kindly suggest the solution.
Integrating Linear Regression in MERN Stack Application: Python or JavaScript?
I’ve developed a restaurant admin panel using the MERN stack (MongoDB, Express.js, React, Node.js) and am now looking to implement linear regression to forecast sales or predict customer flow based on historical data. The backend is entirely in Node.js, but I’m considering Python for the linear regression part due to its extensive libraries and support for data science (like NumPy, pandas, and scikit-learn).
My dilemma is whether to stick with JavaScript/Node.js to keep the stack consistent or to introduce Python into the mix for its superior machine learning capabilities. I am concerned about the potential complexity of integrating Python with the existing Node.js backend and how to manage communication between the two, if that’s the route I choose. On the other hand, I’m also considering the performance and the ease of implementation that Python’s libraries might offer for linear regression tasks.
I would appreciate insights on:
The feasibility and best practices for integrating Python for linear regression into a MERN stack application.
Potential challenges and solutions in managing communication between Node.js and Python if I go down that route.
Recommendations on JavaScript libraries that could handle linear regression effectively if staying within the JS ecosystem is advisable.
Ultimately, I’m looking for guidance on the optimal path forward for incorporating linear regression into my project, weighing the pros and cons of Python vs. JavaScript for this specific use case.
I initially explored implementing linear regression directly within Node.js, hoping to maintain a consistent technology stack. I experimented with a couple of JavaScript libraries, such as simple-statistics for basic statistical operations and mljs for more machine-learning-oriented tasks, expecting them to offer a straightforward way to apply linear regression models to my dataset.
From these libraries, I managed to implement a basic linear regression model in Node.js. My expectation was that this approach would not only suffice for the prediction accuracy I needed but also keep the application deployment and maintenance straightforward by avoiding cross-language integration.
However, the results were mixed. While I was able to develop and run the linear regression model, I encountered two main issues:
Performance and Scalability: The JavaScript solution worked for small datasets, but as I tried scaling up the data size to more closely mirror the real-world usage scenario of the restaurant admin panel, the performance did not meet my expectations. Processing times were longer than anticipated, and I started to worry about the scalability of this solution.
Feature Set and Ease of Use: Although the libraries I used provided the basic functionality for linear regression, I found them lacking in the breadth of features and the ease of advanced statistical analysis compared to what I knew was available in Python's ecosystem (e.g., scikit-learn). For instance, I wanted more sophisticated ways to handle model fitting, diagnostics, and validation to improve prediction accuracy, which seemed more readily accessible in Python libraries.
These experiences led me to consider Python as an alternative for implementing the linear regression part of my project, despite my initial intention to keep everything within the Node.js environment. The expectation here was not only about achieving better performance and scalability but also accessing a richer set of tools for data analysis and machine learning to enhance the functionality and accuracy of the predictions in my restaurant admin panel.