How to use a custom made library - javascript

I have a AWS dependency layer on on folder nodejs/
There is node_modules/ and package.json with npm dependencies
I created a folder called utils/ and my file is util.js
Since it's a layer on AWS, I import using const utils = require('/opt/nodejs/utils/util'); on my app.js
Problem is that my test cases started failing Cannot find module '/opt/nodejs/utils/util' from 'backend/lambdas/cars/app.js'
How can I fix my test case??
const app = require('./app');
describe('lambda', function () {
it('something', async () => {
const response = await app.lambdaHandler();
....
});
});
app.js
const httpStatusCode = require('http-status-codes');
const cors = require('/opt/nodejs/utils/util');
exports.lambdaHandler = async (event) => {
return {
statusCode: httpStatusCode.OK
};
};
PS: This nodejs folder is on the same level as the lambdas folder

You should import like this const utils = require('../nodejs/utils/util')

Related

Jest doesn't recognize awilix container

Here is my code:
babel.config.cjs
module.exports = {
plugins: ['#babel/plugin-transform-modules-commonjs'],
presets: [['#babel/preset-env', { targets: { node: 'current' } }]]
}
jest.config.cjs
module.exports = {
globals: {
"ts-jest": {
isolatedModules: true,
},
},
};
Setup.ts
import awilix from 'awilix';
import express from 'express';
import CognitoSC from './Service/Cognito.js'
import authController from './Controller/Auth.js';
const app = express();
const container = awilix.createContainer({
injectionMode: awilix.InjectionMode.CLASSIC
});
auth.test.ts
import request from 'supertest';
import app from '../Setup.js';
describe('Testing Authentication/Authorization', function() {
it('responds with json', async function() {
const response = await request(app)
.post('/signin')
.send('username=Test')
.send('password=Testtest123$')
expect(response.status).toEqual(200);
expect(response.body.data.success).toEqual(true);
});
});
and I build it with tsc ("module": "es2022"). When I run npx jest I get an error saying
TypeError: Cannot read properties of undefined (reading 'createContainer')
> 8 | const container = awilix.createContainer({
Interesting thing that I noticed is that if I open Setup.js file which is generated by tsc and change the code from
import awilix from 'awilix';
to
const awilix = require('awilix');
and run npx jest, the tests pass without a problem. I'm little lost and can't figure out what is the problem. I also checked inside Setup.js and express is imported without a problem using ES6 syntax but why it can't do the same with awilix?
It doesn't appear that awilix supports modules.
From their readme they say to use const awilix = require('awilix') .
See here for more information about import/require/ES modules/commonJS.

Why can't you read package.json in a builded electron app?

Hello Stackoverflow users!
I am trying to place all of the configuration for the electron app in the package.json file.
Here is my code snippet:
index.js
const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('fs');
function readConf() {
const data = fs.readFileSync('./package.json', 'utf8');
return data;
}
ipcMain.on('synchronous-message', (event, arg) => {
event.returnValue = readConfig();
})
index.html
<script type="text/javascript">
const { ipcRenderer } = require('electron')
config = JSON.parse(ipcRenderer.sendSync('synchronous-message', ''))
</script>
<h1>Version of <script>document.write(config.name)</script> is <script>document.write(config.version);</script></h1>
The code is working when you run the app via npm start, but when you make it into an exe with electron-forge and squirrel (npm make) and try to run it after installing it throws an error that the package.json file can't be found.
So what do you need to specify as the path to the file to read it in the built app?
I am using electron forge.
I found a way to fix the issue!
Instead of
const data = fs.readFileSync('./package.json', 'utf8');
You'll need to write
const data = fs.readFileSync(__dirname + '/../package.json', 'utf8');

Iterate over folder and import index.js

I have create react app code base in which i would like to be able to iterate over a nested structure of data to import one specific file.
I have the following structure:
root.js
-modules
-- mod1
--- index.js
-- mod2
--- index.js
In root.js I would like to go over every module in modules to import index.js so that the initialization data will be run at the start of the application. Its unclear to me what is the best way to do this preferably without using any plugins if there is a solution.
In my opinion, you should include them "manually"
// root.js
require('mod1.index')
require('mod2.index')
// ...
It's more clear and direct. Unless you have 100+ modules
EDIT for dynamic import:
No dependancies proposal (variation of https://gist.github.com/kethinov/6658166#gistcomment-1603591)
'use strict'
const fs = require('fs')
const walkSync = function (dir, filelist) {
const files = fs.readdirSync(dir)
filelist = filelist || []
files.forEach(function (file) {
if (fs.statSync(dir + '/' + file).isDirectory()) {
filelist = walkSync(dir + '/' + file, filelist)
} else {
filelist.push(dir + '/' + file)
}
})
return filelist
}
allFiles = walkSync('./src')
allFiles.filter(f => f.split('/').pop() == 'index.js').forEach(f => require(f))
One dependacie proposal: Get all files recursively in directories NodejS
Turns out this was simple:
Export everything in a modules.js files.
const req = require.context('./', true, /^\.\/[a-zA-Z0-9]+\/index.js$/);
const modules = req.keys().map(req);
module.exports = modules;
Then import the modules.js file in some root.js file.

Engine not found for the ".js" file extension

I want to use koa-views with Koa and Koa-Router with Next.js. In previous projects, I had no issues with express but in this project, I have to use Koa. Using its router, I want to render a page: /some/page/:id. Following the same Nextjs way:
router.get('/some/page/:id', async (ctx, next) => {
const actualPage = '/some/page/id' // id.js (not actual name 😝)
await ctx.render(actualPage, {/* could pass object */})
});
That would work if I was using express. With Koa:
const Koa = require('koa');
const views = require('koa-views');
// const render = require('koa-views-render'); <-- I what's this?
[..] // Making things short here
const server = new Koa();
const router = new Router();
// My issue, I'm seeing tutorials using other engines: .ejs etc
// I'm not using any, I only have .js files
server.use(views(__dirname + "/pages", { extension: 'js' }));
Using the same router.get... function as above, I get:
Error: Engine not found for the ".js" file extension
When I go to /some/page/123, I'd expect it to render the file /pages/some/page/id.js. How?
It turns out I do not need any extra modules to achieve this 🙀
Create a function called, ie, routes then pass app and router as a param
const routes = (router, app) => {
router.get('/some/page/:id', async (ctx) => {
const { id } = ctx.params
const actualPage = '/some/page/id'
// Render the page
await app.render(ctx.req, ctx.res, actualPage, {foo: 'Bar'})
}
}
module.exports = routes
Inside your server.js file:
// const routes = require('./routes);
// const app = next({ dev }); // import other modules for this section
// app.prepare().then(() => {
// const router = new Router();
// [..]
// routes(router, app)
// })
The commented out section is a slim down version to make a point in where things should be.

Organize firebase functions in multiple files | Deploy error

So based on this Medium post I tried to split my firebase functions into different files.
My index.js looks like this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const glob = require("glob");
const camelCase = require("camelcase");
const files = glob.sync('./**/*.f.js', { cwd: __dirname, ignore: './node_modules/**'});
admin.initializeApp(functions.config().firebase);
for(let f=0,fl=files.length; f<fl; f++){
const file = files[f];
const functionName = camelCase(file.slice(0, -5).split('/').join('_')); // Strip off '.f.js'
if (!process.env.FUNCTION_NAME || process.env.FUNCTION_NAME === functionName) {
exports[functionName] = require(file);
}
}
My file test.f.js, where my function is located, is in some subfolders and looks like this:
const functions = require('firebase-functions');
exports.addNew = functions.https.onRequest((request, response) => {
...
})
My subfolders are called "dev" and "User", the file is called "Test" and my function "addNew"
When I try to deploy I get the following error:
⚠ functions[devUserTest-addNew(us-central1)]: Deployment error.
Function load error: Node.js module defined by file index.js is expected to export function named devUserTest.addNew
I hope someone can provide a solution to this problem.
Tanks!

Categories

Resources