Global variables with apollo and express - node.js

index.js
import { ApolloServer } from 'apollo-server-express'
import express from 'express'
global.myTest = true
/models/user.js
import Sequelize from 'sequelize'
console.log('test:' + global.myTest)
Anyone knows how to set global variables with Apollo Server Express ? The example above returns undefined.

Due to es6 import module hoisted. All the dependent Modules will be loaded before running any code. You need to make sure to access the global.myTest after it has been defined and assigned. You can use nodejs require keyword to require your user model after assign value to global.myTest.
E.g.
index.js:
import { ApolloServer } from 'apollo-server-express';
import express from 'express';
global.myTest = true;
require('./models/user');
./models/user.js:
console.log('test:' + global.myTest);
The output of the console:
$ npx ts-node ./index.js
test:true

Related

Unable to import Client from node-pg

I am trying to use Postgresql in a Node project. I am using modular imports, so I am having issues importing 'pg':
import * as pg from 'pg'
const { Client } = pg
let client = new Client()
leading to this error
let client = new Client()
^
TypeError: Client is not a constructor
I've looked at a couple other questions similar to this, but still have issues:
import { native as pg } from 'pg';
let client = new pg.Client()
leading to this error:
import { native as pg } from 'pg';
^^^^^^
SyntaxError: Named export 'native' not found. The requested module 'pg' is a CommonJS module, which may not support all module.exports as named exports.
Does anyone know what I can try to make this import correctly?
From the error suggestion, pg is a CommonModule which may not support all module.exports as named exports.
change the import from
import * as pg from 'pg'
to
import pg from 'pg'
will solve the import problem.

Nestjs: import modules undefined, but methods and functions from modules can be imported

I am using Nestjs with WebStorm & TS 4.2.3^latest.
The problem that I am facing is a bit strange. For example, some modules, like axios can be installed, imported, and used as usual. But some modules, especially Nodejs Core, like fs or path, can't be imported as modules. BUT their methods can be imported and used just fine!
//ERROR: Module undefined on run:dev, but no error in IDE
import path from 'path';
import fs from 'fs';
//Working fine
import { join } from 'path';
import { readFileSync } from 'path';
I am sure, they have correct TS types, even installed manually. For example:
import axios from 'axios';
import path from 'path'; //path is undefined
import { join } from 'path'; // working fine
import { Injectable } from '#nestjs/common';
#Injectable()
export class AppService {
async test(input: string): Promise<void> {
await axios.get() // working fine
await path.join() // Cannot read property 'join' of undefined
//BUT await join() // Works fine!
}
}
I have only one tsconfig.json which is generated by Nest Cli. I am starting my apps via npm start:dev -name and IDE don't show any errors in code, until I ran code.
tsconfig.json module part, just to be sure: "module": "commonjs", package.json doesn't have module part at all.
IDE in this case, misdirect me a bit. Almost forgot, that I am dealing with TS now. Some modules seem to have no default exports, so:
You should import as with them: import * as fs from 'fs';
Or, another option is enabling: "esModuleInterop": true, in your tsconfig.json

Import Inquirer as module in Node 13

I'm having troubles with import of Inquirer using modules in Node 13.12.0. Any other import works well. As long as I've been using Node 12.x with require() it worked well.
My use-case of anything.mjs
import fs from "fs"; // works well
import inquirer from 'inquirer'; // undefined
So I've tried to import only one exported module
import {prompt} from 'inquirer'; // The requested module 'inquirer' does not provide an export named 'prompt'
also tried:
import * as inquirer from 'inquirer'; // [Module] { default: undefined }
I've also tried to require() but it is not defined in modules anymore.
How should I properly import Inquirer in Node 13.12.0 using modules?
According to the docs, you can use require in ESM in Node 13 as follows:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const inquirer = require('inquirer');
inquirer just released v9.0 and migrated to ESM modules.
So now this will simply work:
import inquirer from 'inquirer';
const response = await inquirer.prompt([
{
type: 'input',
name: 'question',
message: 'Want to answer?'
}
]);
console.log(response.question);
Using ES Modules and enquirer 2.3.6 I am using it this way. We could pass types to prompt object.
import enquirer from 'enquirer';
const enquirerObj = new enquirer();
const response = await enquirerObj.prompt({
type:'confirm',
name: 'question',
message: 'Want to answer?'
});
console.log(response);

process.env doesn't show variables outside app.js

app.js
import koa from 'koa';
import http from 'http';
import logger from 'koa-logger';
import koaBody from 'koa-body';
import dotenv from 'dotenv';
import dotenvExpand from 'dotenv-expand';
const config = dotenv.config();
dotenvExpand(config);
console.log(process.env); // Here I see all data which are in my .env file
import { client } from '#pg'; // Inside this file I doesn't see this , but it still after initializing dotenv
#pg = db/connection/index.js
import { Client } from 'pg';
console.log(process.env.DATABASE_URL, 'fds'); // here I don't see the same ( all variables from .env file are undefined)
export const client = new Client({
connectionString: process.env.DATABASE_URL
});
if you need additional info, pls let me know. Pay attention on my comments inside of code snippets, it can be helpful
You need to invoke dotenv in every file you are calling a .env variable.
import dotenv from 'dotenv';
import { Client } from 'pg';
const config = dotenv.config();
console.log(process.env.DATABASE_URL, 'fds');
If you want to call dotenv in all your app files without calling it every time then you need to require it when you run your app:
node -r dotenv/config app.js
If you don't want to use external packages you can just run your script like this :)
I prefer this method.
"start": "sh -ac '. ./.env; node index.js'"
In order to avoid writing
dotenv.config()
in every file, you could just simply add this line of code in your app.js
dotenv.config({ path: path.resolve(__dirname, "path/to/.env") });

export/import javascript class like module node into electron with webpack

In context of basic electon-vue app, I want to create my own javascript class and use it into main process or renderer or into vue component.
I created JS Class but I never find a good way for exporting my class.
All possibility of writing import/export module find in the web finished by same error : Undefined exports
"use strict"
import fs from 'fs'
import typeorm from 'typeorm'
import Public from './../entity/Public'
class ConnectionManager
{
constructor(){}
getConnection(type, name, options) {
}
}
module.exports = ConnectionManager
But it seeams that others js file work perfectly like the vue-router js for routing into vue.js app :
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: require('#/components/Home').default
}
]
})
I package my code with Webpack and libraryTarget Output is : commonjs2
I seems that use babel-loader with webpack
node version : 10.13.0
electron : 3.0.10
Babel : 6
EDIT :
I try this syntax class js file :
"use strict"
import * as fs from 'fs'
import * as typeorm from 'typeorm'
import {Public} from './../entity/Public'
export default class ConnectionManager
{
constructor(){}
getConnection(type, name, options) {
}
}
with this import syntax :
import ConnectionManager from './../service/connectionManager'
But I have this error when I execute code into electron :
Uncaught TypeError:
_service_connectionManager__WEBPACK_IMPORTED_MODULE_8__.default.getConnection
is not a function
I console logged this service class "ConnectionManager" and I have this result (so it really exist) :
ƒ ConnectionManager() {
babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ConnectionManager);
}
It seems that the final js module webpack contain the ConnectionManager class
It seems that you mix commonjs modules with ES modules by the wrong way.
There are a lot of modules (include node built-in) which have no default export. To import such a module you need to use * as moduleAlias or { exportedField } in your import statement. Try to rewrite your code by this way:
import * as fs from 'fs'
import * as typeorm from 'typeorm'
import { Public } from '../entity/Public'
export default class ConnectionManager
{
constructor(){}
getConnection(type, name, options) {
}
}
Because this class is exported as a default value, you can use the following construction to import it as a default field, where ConnectionManager is an alias for the current scope:
import ConnectionManager from '../service/connectionManager'

Resources