replit.com - connecting to mongoose with Secrets - express

I'm new to express.js and mongoose and trying to solve some examples from freeCodeCamp.
I have a strange behaviour and can't find, whats the probleme here.
Connecting to database this way works:
require('dotenv').config();
var mongoose = require('mongoose');
mongoose.connect('mongodb+srv://<user>:<password>#cluster0.omzte.mongodb.net/myFirstDatabase?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true });
Code not working:
connecting with a secret does not work.
the secret is called: MONGO_URI, the value is exactly the same (console.log(mySecret) --> exactly the same String, including also the ' .
require('dotenv').config();
var mongoose = require('mongoose');
var mySecret = process.env['MONGO_URI']
mongoose.connect(mySecret, { useNewUrlParser: true, useUnifiedTopology: true });
What am I missing?
package.json -> dependencies:
"dependencies": {
"body-parser": "^1.15.2",
"dotenv": "^8.2.0",
"express": "^4.12.4",
"mongodb": "^3.6.6",
"mongoose": "^5.12.0"
},
Here is the message inside console (working with Secrets):
Your app is listening on port 3000
(node:1022) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'split' of null
at parseSrvConnectionString (/home/runner/boilerplate-mongomongoose-1/node_modules/mongodb/lib/core/uri_parser.js:50:23)
at parseConnectionString (/home/runner/boilerplate-mongomongoose-1/node_modules/mongodb/lib/core/uri_parser.js:595:12)
at connect (/home/runner/boilerplate-mongomongoose-1/node_modules/mongodb/lib/operations/connect.js:281:3)
at /home/runner/boilerplate-mongomongoose-1/node_modules/mongodb/lib/mongo_client.js:256:5
at maybePromise (/home/runner/boilerplate-mongomongoose-1/node_modules/mongodb/lib/utils.js:685:3)
at MongoClient.connect (/home/runner/boilerplate-mongomongoose-1/node_modules/mongodb/lib/mongo_client.js:252:10)
at /home/runner/boilerplate-mongomongoose-1/node_modules/mongoose/lib/connection.js:834:12
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (/home/runner/boilerplate-mongomongoose-1/node_modules/mongoose/lib/connection.js:831:19)
at /home/runner/boilerplate-mongomongoose-1/node_modules/mongoose/lib/index.js:348:10
at /home/runner/boilerplate-mongomongoose-1/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (/home/runner/boilerplate-mongomongoose-1/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (/home/runner/boilerplate-mongomongoose-1/node_modules/mongoose/lib/index.js:1152:10)
at Mongoose.connect (/home/runner/boilerplate-mongomongoose-1/node_modules/mongoose/lib/index.js:347:20)
at Object.<anonymous> (/home/runner/boilerplate-mongomongoose-1/myApp.js:6:10)
(node:1022) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:1022) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE
define your MONGO_URI in .env file like this
NODE_ENV=development
MONGO_URI=mongodb+srv://<user>:<password>#cluster0.omzte.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
and access it where you need
const mySecret = process.env['MONGO_URI'];
.ENV Usage

Related

How to Hide API key in Preact?

How can i hide api key in preact , in react i used .env file , but don't know how to do it in preact ?
index.js?2e9b:8 Uncaught (in promise) ReferenceError: process is not defined
at eval (index.js?2e9b:8)
at Generator.next (<anonymous>)
at asyncGeneratorStep (index.js:5)
at _next (index.js:7)
at eval (index.js:7)
at new Promise (<anonymous>)
at eval (index.js:7)
at getSeriesInfo (index.js?2e9b:7)
at Object.eval [as __] (index.js?2e9b:14)
at j (index.js?a178:361)
Preact is just a UI library, but I'll assume you're referring to Preact-CLI, which is an actual build tool. Let me know if this is incorrect.
Our wiki covers this under "Use Environment Variables in your Application". process will not exist outside of Node so you'll need to specify the variables you want to use using DefinePlugin.
Add the following to your preact.config.js file:
export default (config, env, helpers) => {
config.plugins.push(
new helpers.webpack.DefinePlugin({
'process.env.MY_VARIABLE': JSON.stringify('my-value'),
}),
);
};
If you specifically want to read from a .env file, you will also need to add some utility to read it, such as dotenv:
import dotenv from 'dotenv';
dotenv.config();
export default (config, env, helpers) => {
config.plugins.push(
new helpers.webpack.DefinePlugin({
'process.env.MY_VARIABLE': JSON.stringify(process.env.MY_VARIABLE),
}),
);
};

Vue refuses to build when I include a local .js file in a template, which references the "window" global - ReferenceError: window is not defined

I have a VuePress project and I just need to include a local js file in a component for a gallery. The .js file is referencing the window object and my project refuses to build:
(node:57059) UnhandledPromiseRejectionWarning: ReferenceError: window is not defined
at isMobile (4.server-bundle.js:1470:27)
at 4.server-bundle.js:3343:20
at 4.server-bundle.js:937:109
at Object.345 (4.server-bundle.js:942:3)
at __webpack_require__ (server-bundle.js:27:30)
at Module.356 (4.server-bundle.js:5022:17)
at __webpack_require__ (server-bundle.js:27:30)
(node:57059) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 49)
(node:57059) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
From the docs I understand I'm only supposed to reference window in the mounted lifecycle method. But what about other scripts? How do I deal with that?
Here is how I'm including the script:
</template>
<script>
import * as GLightbox from '../assets/scripts/glightbox.js'
export default {
// ...
And here is how I'm using it:
// ...
mounted: function () {
this.lightbox = GLightbox({
touchNavigation: true,
loop: true
})
},
Cheers

UnhandledPromiseRejectionWarning: Error: Protocol error (Runtime.callFunctionOn): Promise was collected

Once all tests finish successfully this exception occurs on the Circle CI:
W20200612-14:11:02.429(0)? (STDERR) (node:642) UnhandledPromiseRejectionWarning: Error: Protocol error (Runtime.callFunctionOn): Promise was collected
W20200612-14:11:02.429(0)? (STDERR) at Promise (/home/jenkins/humly-home/packages/hrm/node_modules/puppeteer/lib/Connection.js:183:56)
W20200612-14:11:02.429(0)? (STDERR) at new Promise (<anonymous>)
W20200612-14:11:02.429(0)? (STDERR) at CDPSession.send (/home/jenkins/humly-home/packages/hrm/node_modules/puppeteer/lib/Connection.js:182:12)
W20200612-14:11:02.429(0)? (STDERR) at ExecutionContext._evaluateInternal (/home/jenkins/humly-home/packages/hrm/node_modules/puppeteer/lib/ExecutionContext.js:107:44)
W20200612-14:11:02.429(0)? (STDERR) at ExecutionContext.evaluateHandle (/home/jenkins/humly-home/packages/hrm/node_modules/puppeteer/lib/ExecutionContext.js:57:17)
W20200612-14:11:02.430(0)? (STDERR) at ExecutionContext.<anonymous> (/home/jenkins/humly-home/packages/hrm/node_modules/puppeteer/lib/helper.js:112:23)
W20200612-14:11:02.430(0)? (STDERR) at WaitTask.rerun (/home/jenkins/humly-home/packages/hrm/node_modules/puppeteer/lib/DOMWorld.js:570:65)
W20200612-14:11:02.430(0)? (STDERR) at <anonymous>
W20200612-14:11:02.430(0)? (STDERR) at process._tickDomainCallback (internal/process/next_tick.js:229:7)
W20200612-14:11:02.430(0)? (STDERR) => awaited here:
W20200612-14:11:02.430(0)? (STDERR) at Function.Promise.await (/home/jenkins/.meteor/packages/promise/.0.11.2.1bomg6e.mbyx++os+web.browser+web.browser.legacy+web.cordova/npm/node_modules/meteor-promise/promise_server.js:56:12)
W20200612-14:11:02.430(0)? (STDERR) at Promise.asyncApply (packages/meteortesting:browser-tests/browser/puppeteer.js:64:5)
W20200612-14:11:02.430(0)? (STDERR) at /home/jenkins/.meteor/packages/promise/.0.11.2.1bomg6e.mbyx++os+web.browser+web.browser.legacy+web.cordova/npm/node_modules/meteor-promise/fiber_pool.js:43:40
W20200612-14:11:02.430(0)? (STDERR) (node:642) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 9)
W20200612-14:11:02.431(0)? (STDERR) (node:642) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Too long with no output (exceeded 1m0s): context deadline exceeded
After the investigation, I have found out that this is caused by unit tests using enzyme' shallow rendering. Once I remove these tests everything is fine, but I can't find anything wrong in them.
Also, this exception occurs every once in a few runs (2 - 3). Here is the typical unit test that makes this issue happen:
import React from "react";
import { expect } from "chai";
import { shallow, configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
// import sinon from "sinon";
import ExampleView from "./ExampleView";
configure({ adapter: new Adapter() });
const defaultProps = {
name: "test name",
text: "test value",
};
describe(".../ExampleView", () => {
before(() => {
// methods stubs
});
after(() => {
// restores
});
it("rendering component", () => {
const props = {
...defaultProps,
};
const wrapper = shallow(<ExampleView {...props} />);
const specificElement = wrapper.find(".specific-class-name");
expect(specificElement.text()).to.be.equal(defaultProps.text);
});
});
I think this is something related with meteortesting:mocha package and puppeteer, or maybe in between them. Here is the script I use to run unit tests on CI:
#!/bin/bash -eu
cd "$(dirname "${BASH_SOURCE[0]}")"/..
export PORT="${PORT:-5000}"
export ROOT_URL="http://localhost:${PORT}"
export TEST_BROWSER_DRIVER=puppeteer
export MOCHA_TIMEOUT=6000
cd node_modules/puppeteer/.local-chromium/linux-*/chrome-linux/
sudo chown root:root chrome_sandbox
sudo chmod 4755 chrome_sandbox
sudo cp -p chrome_sandbox /usr/local/sbin/chrome-devel-sandbox
export CHROME_DEVEL_SANDBOX=/usr/local/sbin/chrome-devel-sandbox
cd ../../../../../
meteor test --once --driver-package meteortesting:mocha --port "${PORT}" "$#"
I have tried with "-- --exit" in last command trying to force mocha to exit after all tests get done, but it does not help. Here is the list of versions I have:
meteor 1.8.3
node 8.17.0
puppeteer 1.20.0
meteortesting:browser-tests#1.3.1
meteortesting:mocha#1.1.3
meteortesting:mocha-core#6.2.2
react 16.12.0
sinon 7.5.0
chai 4.2.0
enzyme 3.10.0

Vuetify & Webpack Encore compilation error

I created (currently standalone) and API and a VueJs (with Vuetify) App and wanted to combine both using the webpack encore bundle for Symfony.
But when I want to build the frontend app, I get this error when executing yarn run encore dev:
(node:12500) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
at items.forEach.item (/Users/pguetschow/Projects/hosting-tool/node_modules/vuetify-loader/lib/loader.js:21:60)
at Set.forEach (<anonymous>)
at Object.getMatches (/Users/pguetschow/Projects/hosting-tool/node_modules/vuetify-loader/lib/loader.js:16:9)
at Object.module.exports (/Users/pguetschow/Projects/hosting-tool/node_modules/vuetify-loader/lib/loader.js:106:64)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:12500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
This is my webpack.config.js
const Encore = require('#symfony/webpack-encore');
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin');
Encore
.setOutputPath('public/build/')
.setPublicPath('/build')
.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())
.cleanupOutputBeforeBuild()
.addEntry('js/main', './assets/js/main.js')
.enableVueLoader()
.enableBuildNotifications(true)
.addPlugin(new VuetifyLoaderPlugin())
;
module.exports = Encore.getWebpackConfig();
Any idea? The standalone app is working fine, I simply moved it to the assets/js folder. I require vuetify-loader ^1.2.2 for this.
And this is my main.js:
import Vue from 'vue'
import App from './App.vue'
import Vuetify from 'vuetify/lib'
import MultiFiltersPlugin from './plugins/MultiFilters'
import 'vuetify/src/stylus/app.styl'
import 'material-design-icons-iconfont/dist/material-design-icons.css'
import 'vuetify/dist/vuetify.min.css'
Vue.use(MultiFiltersPlugin);
Vue.use(Vuetify, {
iconfont: 'md',
});
new Vue({render: h => h(App),}).$mount('#app');
Here's an example webpack.config.js file from this working example that shows how to get Symfony and Vuetify (v.2x) to play nice together:
var Encore = require('#symfony/webpack-encore');
// import vuetify-loader as a plugin here
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin')
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}
Encore
.setOutputPath('public/build/')
.setPublicPath('/build')
.enableVueLoader() // <-- IMPORTANT: this loads Vue
// NOTE: I put my Vue app in assets/vue which I think is non-standard
// but it allows me to structure my Vue app as I would in a non-Symfony app
.addEntry('app', './assets/vue/main.js')
.splitEntryChunks()
.enableSingleRuntimeChunk()
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
.enableVersioning(Encore.isProduction())
.configureBabel(() => {}, {
useBuiltIns: 'usage',
corejs: 3
})
// add VuetifyLoaderPlugin: THIS loads all of the Vuetify components
.addPlugin(new VuetifyLoaderPlugin())
// enables Sass/SCSS support
.enableSassLoader(options => {
options.implementation = require('sass')
options.fiber = require('fibers')
})
;
module.exports = Encore.getWebpackConfig();
Caveat, I'm not really a symfony developer, but this worked for me. HTH!

ReferenceError: ReadableStream is not defined while running jest tests

My web app reads local files using a custom ReadableStream (in-order that I won't need to have a max file size that the platform supports) and it works great, both for correctly formatted files and error files. My app is built using React-Redux-Saga.
I'm now attempting to add limited e2e tests to my code to test the state management. I'm testing that when sending redux actions the state updates correctly. I'm testing the saga's using the package redux-saga-tester.
While running the jest client tests that read local files using the ReadableStream I built, I got an error ReferenceError: ReadableStream is not defined. What I understood is that the jsdom environment that jest uses is missing the ReadableStream implementation. I than added the web-streams-polyfill package to polyfill the ReadableStream class.
Now the validate file test is passing as in the browser:
test('Select and validate log file', async () => {
const testFile = testFileBuilder.valid();
storeTester.dispatch(fileSelected(testFile));
await storeTester.waitFor(FILE_VALIDATED);
const state = storeTester.getState().file;
expect(state.fileValidated).toBeTruthy();
});
My problem is that when I run a second validation test with an invalid file the test passes but prints an error to the console.
The test:
test('Select an invalid file - JSON error', async () => {
const testFile = testFileBuilder.errorJSON();
storeTester.dispatch(fileSelected(testFile));
await storeTester.waitFor(FILE_ERROR);
const state = storeTester.getState().file;
expect(state.fileValidated).toBeFalsy();
expect(state.fileError).toBeTruthy();
});
The error that is printed after the test completes successfully:
e.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Error: connect ECONNREFUSED 127.0.0.1:80
at Object.dispatchError (/home/noams/dev/web/visual-log-viewer/client/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:65:19)
at Request.client.on.err (/home/noams/dev/web/visual-log-viewer/client/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:676:20)
at Request.emit (events.js:194:15)
at Request.onRequestError (/home/noams/dev/web/visual-log-viewer/client/node_modules/request/request.js:881:8)
at ClientRequest.emit (events.js:189:13)
at Socket.socketErrorListener (_http_client.js:392:9)
at Socket.emit (events.js:189:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19) undefined
Any subsequent file validation tests fail.
I'd appreciate any advice of how to tackle this issue.