nestjs issue with variable in .env file - javascript

Im using NestJS framework to build a rest api, i have a issue getting the environment variables.
I have a .env with a variable "SMB_SHARE" with a path string, when i pass this variable to a class constructor of a smb2 libray, this throw an error, the string provided by the environment variable is invalid.
The environment variable is this:
SMB_SHARE=\\10.00.0.000\some_path
When i use console log in the code the variable is ok, is a string and has the correct string value. But when i pass it to the constructor, it throw the error.
I pass the string directly to the constructor, and it work fine, the others environment variables of the constructor are setted correctly (like the username and password). Only the SMB_SHARE variable is throwing the error.
I dont have idea what is the problem here. Can someone help me with this issue?
I show some examples:
constructor(private config: ConfigService) {
console.log('VAR', config.get<string>('SMB_SHARE'));
//This show the correctly string variable value
const share = config.get<string>('SMB_SHARE');
this.sambaClient = new SMB2({
share: '\\\\10.00.0.000\\some_path', //WORK
//share: share, FAIL
//share: config.get<string>('SMB_SHARE'), FAIL
//share: process.env.SMB_SHARE, FAIL
domain: '',
username: config.get<string>('SMB_USERNAME'),
password: config.get<string>('SMB_PASSWORD'),
debug: true,
autoCloseTimeout: 0,
})
}
The .env file is like this:
SMB_SHARE=\\\\10.00.0.000\\some_path
SMB_USERNAME=user
SMB_PASSWORD=secret

More than likely, what is happening is JavaScript is escaping the extra \. This is unescaped when the print happens, so it looks proper (i.e. console.log(process.env.SMB_SHARE) will print \\\\10.0.0.0\\some_path, but in reality, the variable is now \\\\\\\\10.0.0.0\\\\some_path). I ended up creating a mock of this using a text file called ./temp/.env and making use of the fs module from Node (which is what dotenv uses, which is what #nestjs/config uses. You can see below the cat (print) of the file, and the two different methods while using node to read the file
~/Documents/code
▶ cat ./temp/.env
HOST=\\\\127.0.0.1:3000\\path
~/Documents/code
▶ node
Welcome to Node.js v12.18.2.
Type ".help" for more information.
> const { readFileSync } = require('fs');
undefined
> readFileSync('./temp/.env').toString()
'HOST=\\\\\\\\127.0.0.1:3000\\\\path\n\n'
> console.log(readFileSync('./temp/.env').toString())
HOST=\\\\127.0.0.1:3000\\path
The solution here, would be to change your .env file to be the exact string you're wanting to pass on to the configuration (probably \\10.0.0.0\some_path)

you have to implement the config module.
start with
npm i --save #nestjs/config
then add the configModule in your appModule:
import { ConfigModule } from '#nestjs/config';
#Module({
imports: [ConfigModule.forRoot()],
})
export class AppModule {}

Related

cy.type() can only accept a string or number. You passed in: undefined cypress error

When I run this code, it gives error. I am not getting what am I doing wrong with this.
export class Login{
enterEmail(){
return cy.get('input[type="email"]').type(Cypress.env('USER_LOGIN_EMAIL'))
}
enterPassword(){
return cy.get('input[type="password"]').type(Cypress.env('USER_LOGIN_PASSWORD'))
}
signInBtn(){
return cy.get('button[data-cy="login_signin_button"]').click()
}
}
As ChrisG said, one of either Cypress.env('USER_LOGIN_EMAIL') or Cypress.env('USER_LOGIN_PASSWORD') is undefined. You can define environment variables in multiple ways, but I would suggest, if these values are going to be static, to define them in your configuration.
how are you? There are a some points we need to check, to understand why you are getting undefined.
First we need to understand where those environment variables are saved, they could be saved in a cypress.env.json file or in another .env file.
If they are saved in a cypress.env.json file, check if this file is in a JSON format like bellow with the correct variable names:
{
"USER_LOGIN_EMAIL": "some.email#gmail.com",
"USER_LOGIN_PASSWORD": "some.password"
}
If they aren't in a cypress.env.json but they are in another .env file, your environment variables in this other file should have a prefix CYPRESS_ so their correct names should be:
CYPRESS_USER_LOGIN_EMAIL
CYPRESS_USER_LOGIN_PASSWORD
If your environment variables don't exist in any .env file you can create the cypress.env.json like above or you can manually export in the terminal before running Cypress each time you open a new terminal using:
export CYPRESS_USER_LOGIN_EMAIL=some.email#gmail.com
export CYPRESS_USER_LOGIN_PASSWORD=some.password

Access environment variables from client [duplicate]

This question already has answers here:
next.js environment variables are undefined (Next.js 10.0.5)
(8 answers)
Dynamic access of environment variables in NextJS not working
(1 answer)
Closed last year.
I'm making a lot of API calls from within my components using fetch. Everytime I had to write this logic to determine which environment I'm in So, I created a Utils class which returns the correct base url:
export default class Utils {
static get baseUrl() {
const inDev = process.env.NODE_ENV !== 'production';
const { NEXT_PUBLIC_DEV_URL, NEXT_PUBLIC_PROD_URL } = process.env;
return inDev ? NEXT_PUBLIC_DEV_URL : NEXT_PUBLIC_PROD_URL;
}
}
But now I'm getting this error when my component loads:
ReferenceError: process is not defined
I looked around and found that I need to mark my variables as NEXT_PUBLIC so I did but the problem still persists. What's the ideal way to handle this?
If you want to expose ENV variables to the client you can use publicRuntimeConfig inside your NextJS configuration (next.config.js). Here is how you could do it:
publicRuntimeConfig: {
myEnvVar: process.env.MY_ENV_VAR
}
And then in the file you would like to use your ENV variable:
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();
const envVar = publicRuntimeConfig.myEnvVar // store in it a 'const' or do whatever you want with it,;
Your class can actually look like this :-
export default class Utils {
static get baseUrl() {
return process.env.NEXT_PUBLIC_URL;
}
}
The NEXT_PUBLIC prefix should work well for inlining the values which are replaced at build time and sent to the browser as per docs.
In your .env.development (or whatever your dev environment file is called) file, you can have NEXT_PUBLIC_URL pointing to http://localhost:8000 and in your production you will probably have production env variables setup using a GUI (like in Netlify or Vercel), so there NEXT_PUBLIC_URL can be https://blablasite.com.
Either way, NEXT_PUBLIC prefix will ensure that at build time those values are picked up and inlined before sending the same to browser.

ReferenceError: VUE_APP_CONFIG is not defined Jest unit tests failing

export interface VueAppConfig {
API_URL: string;
API_URL_V2: string;
}
declare const VUE_APP_CONFIG: VueAppConfig;
export const APP_CONFIG = { ...VUE_APP_CONFIG } as const;
In above code am getting reference error.
declare tells the compiler that the variable already exists somewhere. It's not actually creating the variable.
If you're trying to create the variable, remove declare.
Given the name (VUE_APP_CONFIG), I'm guessing you're trying to read an environment variable, where the VUE_APP_ prefix makes the variable avaiable in the production build. In that case, make sure to refer to it via process.env:
const VUE_APP_CONFIG = JSON.parse(process.env.VUE_APP_CONFIG) as VueAppConfig
Problem was: jest was not receiving this value am not sure why, but after updating jest.config.js to accept
globals: {
VUE_APP_CONFIG: true,
},
it all started working fine

process.env.FOO transformed into {}.FOO and throwing error "expected expression, got "."

I wrote a TypeScript module that interacts with a specific RESTful API. The module never refers to process.env anywhere (target is browser, possibly Node down the line as well).
I use Rollup to transpile to a single JS file. From there, going into Node and require('./build/index') is successful, and I can even run the functions and get expected results. So Rollup itself appears to work.
But the file contains many references to things like process.env.DEBUG. (I suspect Rollup is doing something to create loggers that can work in both Node and browser.)
Now I import this into a Gatsby UI project that will need to connect to the API using this module:
import { api } from 'my-api'
api.someApiCall()
Problem is that when Gatsby compiles all this (using Webpack?) into commons.js (some big JS file with a lot of combined code from different libraries, including my API module), it appears to transform the module's process.env.DEBUG (for example) into {}.DEBUG. Then the browser complains that "expected expression, got '.'". Which makes sense. You cannot access {}.DEBUG. It would have to be ({}).DEBUG or const o = {}; o.DEBUG.
Now I have been off in the world of other languages for a while. Rollup is fairly new to me. Gatsby is very new to me. What is the way forward? Do I tell Rollup via a config to replace process.env with ({}) so that way ? But then that precludes the library from ever being used in Node.js and taking advantage of process.env.
Do I need to change something about Gatsby to have it replace process.env with ({})?
Edit For example, here is some output showing up in my browserin commons.js:
function save(namespaces) {
if (null == namespaces) {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete {}.DEBUG;
} else {
{}.DEBUG = namespaces;
}
}
/**
* Load `namespaces`.
*
* #return {String} returns the previously persisted debug modes
* #api private
*/
function load() {
return {}.DEBUG;
}
In my module, those are process.env.DEBUG.
Edit 2 I've also tried putting a gatsby-node.js containing this:
exports.onCreateWebpackConfig = ({
plugins,
actions,
}) => {
const { setWebpackConfig } = actions;
setWebpackConfig({
plugins: [
plugins.define({
'process.env': "({})",
'{}.DEBUG': '({}).DEBUG',
})
]
})
}
No effect.

Testing URL query string in nodejs

Hey everyone I made a package that can manage and control URL query strings.
I publish it throw npm. and wrote some tests to the core of the package
"parser.js" - that parse the query string to an object
"strigifyer.js" - that make an object to URL query string
I test those files for now with "mocha" and "expect"
there is one main file that manage the above files and the file is also push to query string to URL without refresh. it uses the window.history object.
what should I do to success to test the main file (index.js)?
I need the window and history objects to check if there is a change after I use my api.
here is the package if its help:
https://github.com/nevos12/query-string-manager
thank you.
If I understood correct, the module that exposes your library is src/index.js
From the code style of your index.js, I'd suggest to use sinon to test your code flow.
A unit test could be :
import sinon from 'sinon'
import qs from 'src/index.js'
it('should reset queryStringObject', () => {
const pushToUrlSpy = sinon.spy(qs, 'pushToUrl');
qs.reset(true);
expect(qs.queryStringObject).to.equal({});
expect(pushToUrlSpy.called);
pushToUrlSpy.restore();
})
This code creates a spy on pushToUrl() , invokes reset() and asserts that queryStringObject is an empty object now and pushToUrl() was invoked as least once. In the end it restores the spy, otherwise other tests might act weird.

Categories