Use process.env inside imported const in jest - import

I have a config file that exports some info for my app.
export const config: Config = {
isProd: process.env.NODE_ENV == 'production',
connection: {
port: parseInt(process.env.APP_PORT) || 2000,
},
};
And I want to import it and use inside my e2e jest test.
import {Test, TestingModule} from "#nestjs/testing";
import {INestApplication} from "#nestjs/common";
import * as request from "supertest";
import {AppModule} from "./../src/app.module";
import * as dotenv from "dotenv";
dotenv.config({path: ".env"});
import {config} from "../src/infrastructure/config/config"
console.log(process.env); // available here
console.log(config); // will return default values, not from .env
// ...
How can i make jest use env inside imported module?

Nestjs has great configuration modules that support .env:
https://docs.nestjs.com/techniques/configuration#custom-env-file-path
Makes it really easy to ref your configuration in all of your services as opposed to having to import.

Related

No migrations are pending using Typeorm CLI and NestJS

The issue I'm facing is with running migrations using #nestjs/typeorm ^9.0.1 and typeorm ^0.3.12. Despite being able to build the project and create migrations, when I try to run them, typeorm can't find the migration files (No migrations are pending).
I have noticed that the version 0.3.x of typeorm requires Datasource object and that in the version 9.x of #nestjs/typeorm, TypeOrmModuleOptions does not have the cli : {migrationsDir : string} attribute.
Here's a link to the project that reproduces the problem, and an example directory structure :
src\configs\database\dataSource.config.ts
src\configs\database\postgres.config.ts
src\configs\database\migrations\1676252827402-Chat.ts
postgres.config.ts
import { DataSourceOptions } from "typeorm";
import { join } from "path";
import { config } from "dotenv";
import CustomNamingStrategy from "./customNamingStrategy";
import { registerAs } from "#nestjs/config";
import { TypeOrmModuleOptions } from "#nestjs/typeorm";
config();
export const databaseConfig: DataSourceOptions = {
name: "default",
type: "postgres",
url: process.env.DATABASE_URL,
ssl:
process.env.DATABASE_ENABLE_SSL === "true"
? {
rejectUnauthorized: false,
}
: false,
logging: process.env.DATABASE_ENABLE_LOGGING === "true",
entities: [join(__dirname, "../../models/*/", "*.entity.{ts,js}")],
migrations: [join(__dirname, "migrations/*.{ts,js}")],
synchronize: false,
migrationsRun: false,
namingStrategy: new CustomNamingStrategy(),
};
export default registerAs(
"database",
() =>
({
...databaseConfig,
keepConnectionAlive: true,
} as TypeOrmModuleOptions)
);
dataSource.config.ts
import { DataSource } from "typeorm";
import { databaseConfig } from "./postgres.config";
export const AppDataSource = new DataSource(databaseConfig);
package.json
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli"
"migration:create": "yarn run typeorm migration:create"
"migration:run": "yarn run typeorm migration:run -d src/configs/database/dataSource.config.ts"
Although I can use the create command successfully, when I use the run command, it only displays the message "No migrations are pending". I attempted to resolve the issue by changing migrations path to the DataSourceOptions.migrations list, but it did not work. I also tried replacing the cli parameter datasource with the dist datasource, as well as adjusting the migration paths, but these changes did not fix the issue.
I'm facing a similar issue using the same version of typeorm (^0.3.12), so there might be a bug in this version.
It seems that the migrations are not found anymore if the DataSourceOptions.migrations property is set with the path to the migrations folder.
The ^0.3.12 version seems to be working fine only if the migration classes are directly referenced in DataSourceOptions.migrations, similar to the following:
import { Chat1676252827402 } from './migrations/1676252827402-Chat.ts';
export const databaseConfig: DataSourceOptions = {
...
migrations: [Chat1676252827402],
...
};

Nuxt 3 "component library" module does not expose mixins of exported components in NX monorepo

I'm facing a problem with my Nuxt 3 component library.
It contains several Vue components which are then added to the exported components
export const useComponents = (nuxt: Nuxt) => {
const __dirname = dirname(fileURLToPath(import.meta.url));
let componentsDirectory = join(__dirname, "../", '/components');
nuxt.hooks.hook("components:dirs", (dirs) => {
dirs.push({
path: join(componentsDirectory, "../", 'atoms'),
prefix: 'base',
});
dirs.push({
path: join(componentsDirectory, "../", 'layout'),
prefix: 'base',
});
dirs.push({
path: join(componentsDirectory, "../", 'molecules'),
prefix: 'base',
});
})
}
However, some of those components are using mixins, which are located next to the components and relatively imported.
When using that component library in my application, it does not find the mixins and I'm getting this exception:
when using import loginButtonsMixing from "~/src/molecules/loginButtonsMixing.js";
[vite:load-fallback] Could not load
/home/user/workspace/my-project/apps/my-app/molecules/loginButtonsMixing.js
(imported by
../../../libs/general/base/src/molecules/LoginButtons.vue): ENOENT: no
such file or directory, open
'/home/user/workspace/my-project/apps/my-app/molecules/loginButtonsMixing.js'
It looks inside the app directory, instead of the library directory.
And when I'm using import loginButtonsMixing from "./loginButtonsMixing.js";
Could not resolve './loginButtonsMixing.js' from
../../../libs/base/src/molecules/LoginButtons.vue at error
(/home/user/workspace/my-project/node_modules/rollup/dist/es/shared/rollup.js:1858:30)
at ModuleLoader.handleResolveId
(/home/user/workspace/my-project/node_modules/rollup/dist/es/shared/rollup.js:22156:24)
at
/home/user/workspace/my-project/node_modules/rollup/dist/es/shared/rollup.js:22119:26
The path looks more or less correct, but rollup seems to fail.
How do I tell the Nuxt module to expose them as well?

babel enable import of each dir from root without relative

My root dir structure is like so:
src
utils
types
clients
package.json
etc.
my current babel config i run is like:
{
presets: ['#babel/preset-env', '#babel/preset-typescript', '#babel/preset-react', '#babel/preset-flow'],
plugins: ['#babel/plugin-syntax-dynamic-import', '#babel/transform-runtime'],
env: {
build: {
ignore: ['**/*.spec.tsx', '**/*.spec.ts', '**/*.stories.tsx']
}
},
ignore: ['node_modules']
}
How do I allow various /src files directly imports from root. eg.
import { handyFunction } from 'utils'
import { api } from 'clients'
as opposed to doing this relatively:
import { handyFunction } from '../../../utils'
import { api } from '../../../clients'
You can use babel plugin module resolver as mentioned here https://www.npmjs.com/package/babel-plugin-module-resolver.

NestJS: Resolving dependencies in NestMiddleware?

I'm trying to combine express-session with a typeorm storage within NestJS framework. Therefore I wrote a NestMiddleware as wrapper for express-session (see below). When I start node, NestJS logs the following
Error message:
UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 1): Error: Nest can't resolve dependencies of the
SessionMiddleware (?). Please verify whether [0] argument is available
in the current context.
Express is not started (connection refused), but the Sqlite DB (where the sessions should be stored) is created (also a session table, but not the columns).
To me it looks like there is a special problem in resolving dependencies with #InjectRepository from nestjs/typorm-Module. Does anyone have a hint?
Code:
import { Middleware, NestMiddleware, ExpressMiddleware } from '#nestjs/common';
import * as expressSession from 'express-session';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository } from 'typeorm';
import { TypeormStore } from 'connect-typeorm';
import { Session } from './session.entity';
#Middleware()
export class SessionMiddleware implements NestMiddleware {
constructor(
#InjectRepository(Session)
private readonly sessionRepository: Repository<Session>
) {}
resolve(): ExpressMiddleware {
return expressSession({
store: new TypeormStore({ ttl: 86400 }).connect(this.sessionRepository),
secret: 'secret'
});
}
}
It was my fault. Had the middleware in a module, but was configuring the session middleware at the app module level. On that level the following import statement was missing:
TypeOrmModule.forFeature([Session])
Moved now everything to non-app module including middleware configuration. That solved the problem.

Babel 7 and babel-polyfill

After updating to babel 7 beta, looks like babel polyfill does not transpile before bundle. I updated all scoped packages like this one "#babel/polyfill": "7.0.0-beta.36". And changed imports for two files from import 'babel-polyfill' to import '#babel/polyfill'. How to use babel/pollyfill with babel env and babel 7. Should I use babel/polyfill when use useBuiltIns: 'usage', with targets?
.babelrc.js
const nodeEnv = process.env.NODE_ENV || 'development'
let presetEnvConfig, plugins
if (nodeEnv === 'test'){
presetEnvConfig = {targets: {node: 'current'}}
plugins = ['istanbul']
} else {
presetEnvConfig = {
targets: {
browsers: ['last 2 versions', 'ie >= 11']
},
modules: false
}
plugins = ['react-hot-loader/babel']
}
const config = {
presets: [
['#babel/preset-env', presetEnvConfig],
'#babel/react',
'#babel/stage-2'
],
plugins,
}
types.js
import keyMirror from '../../../utils/keyMirror'
export default keyMirror({
Unassign: null,
Reassign: null,
QuickAssignment: null,
}, 'TagAssignmentTypes')
index.js
<Assignment
assignee={assignee}
tagId={tagId && tagId.toString(16)}
assignmentType={assignmentTypes.Reassign}
onRequestClose={() => this.setState({isAssignmentInProgress: false})}
onChange={onChange}
/>
#babel/polyfill is a wrapper package which only includes imports of stable core-js features (in Babel 6 it also included proposals) and regenerator-runtime/runtime, needed by transpiled generators and async functions. This package doesn't make it possible to provide a smooth migration path from core-js#2 to core-js#3: for this reason, it was decided to deprecate #babel/polyfill in favor of separate inclusion of required parts of core-js and regenerator-runtime.
Instead of
import "#babel/polyfill";
you should use those 2 lines:
import "core-js/stable";
import "regenerator-runtime/runtime";
Don't forget install those dependencies directly!
npm i --save core-js regenerator-runtime
Change
#babel/stage-2 to #babel/preset-stage-2
The following worked for me, add
**.babelrc**
{
"presets": [
["#babel/env"]
]
}
**app.js**
import "core-js/stable";
import "regenerator-runtime/runtime";
*Install as pointed by gianmarco*
npm i --save core-js regenerator-runtime