missing db argument error when connecting gridfs multer and mongodb - express

I am using gridfs and mutler to upload files likes ppt pdf etc..to mongodb atlas. When setting up router its keeps saying db not found I have my uri in a config file.What am i missing here in mongodb atlas i have 3 collections in a database called 'test' do i have to create another db in the cluster? Please help
if (!db) throw new Error('missing db argument\nnew Grid(db, mongo)');
^
Error: missing db argument new Grid(db, mongo)
at new Grid (/Users/ezana/Desktop/Canvas/backend/node_modules/gridfs-stream/lib/index.js:25:18)
at Grid (/Users/ezana/Desktop/Canvas/backend/node_modules/gridfs-stream/lib/index.js:19:12)
at Object. (/Users/ezana/Desktop/Canvas/backend/api/routes/fileUploadRoutes.js:9:11)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object. (/Users/ezana/Desktop/Canvas/backend/app.js:7:21)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
const router = require('express').Router();
const multer = require('multer');
const db = require('./config/main').mongoURI;
const {
mongo,
connection
} = require('mongoose');
const Grid = require('gridfs-stream');
Grid.mongo = mongo;
const gfs = Grid(connection.db);
const storage = require('multer-gridfs-storage')({
db: connection.db,
file: (req, file) => {
return {
filename: file.originalname
}
}
});

const mongoose = require("mongoose");
const multer = require("multer");
const Grid = require("gridfs-stream");
const GridFsStorage = require("multer-gridfs-storage");
const db = mongoose.connection;
let gfs;
db.once("open", function() {
gfs = Grid(db.db, mongoose.mongo);
});
const storage = new GridFsStorage({
url:
url,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString("hex") + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: "uploads"
};
resolve(fileInfo);
});
});
}
});
This worked for me.

Related

Short stack trace with async await in protractor 7

I'm trying to automate some tests with protractor and jasmine and I'm using async/await to resolve the promises.
The issue is, when an error does happen, the stack trace is TOO short and thus, I can't seem to locate the source of the issue.
I did make sure to put SELENIUM_PROMISE_MANAGER to FALSE in the config file.
I'm using protractor 7 along with node 14.16.0
Does anyone know how to solve this ? There are not enough details
Here's a code snippet
const invoicesButton: Button = new Button("Invoices", LocatorType.Href, "#/Invoices");
describe("Kouka test", function () {
beforeEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000000000;
});
it("Does a random test", async function () {
await browser.get("https://appdev.expensya.com/Portal/#/Login?lang=en");
await loginEmailInput.typeText("amr.refacto#yopmail.com")
await loginPasswordInput.typeText("a")
await loginButton.click(true);
await dashboardPage.invoicesButton.click().catch((e) => {
e.stackTraceLimit = Infinity;
throw e;
});
await userInvoicesPage.createManualInvoice(invoice).catch((e) => {
e.stackTraceLimit = Infinity;
console.error("TEST ERROR ", e);
throw e;
});
await browser.sleep(10000);
});
});
And here's the definition of the "Button" Class:
import { browser } from "protractor";
import { WebComponent } from "./webComponent";
export class Button extends WebComponent {
/**
* #param webElementText Text that the web element contains.
* #param locatorType Locator type of the web element to search for.
* #param locator Locator of the web element to search for.
* #param parentElement Parent Web Component if it exists.
*/
constructor(webElementText, locatorType, locator, parentElement: WebComponent = null) {
super(webElementText, locatorType, locator, parentElement);
}
async click(usingJavaScript = false) {
if (usingJavaScript) {
await this.isPresent();
await browser.executeScript("arguments[0].click();", await this.webElement)
}
else {
await this.isVisible();
await this.isClickable();
await this.webElement.click();
}
}
}
Finally, here's the stack trace
Started
Jasmine started
undefined
F
Kouka test
× Does a random test
- Failed: Wait timed out after 10012ms
at C:\Users\Amrou Bellalouna\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2201:17
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
From asynchronous test:
Error
at Suite.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:20:5)
at Object.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:15:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
Failures:
1) Kouka test Does a random test
Message:
Failed: Wait timed out after 10012ms
Stack:
TimeoutError: Wait timed out after 10012ms
at C:\Users\Amrou Bellalouna\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2201:17
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
From asynchronous test:
Error
at Suite.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:20:5)
at Object.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:15:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
1 spec, 1 failure
Finished in 19.461 seconds
I remember trying to solve this a while ago and I couldn't. But I implemented a bunch of workarounds and apparently this was enough
To begin, can you share what these are doing
await this.isPresent();
await this.isVisible();
await this.isClickable();
Having this function
async isVisible(){
await browser.wait(
ExpectedConditions.visibilityOf(this.webElement),
this._elapsedTime
)
}
you can use an advantage of third argument of browser.wait as described here and include an optional message on failure like this
async isVisible(){
await browser.wait(
ExpectedConditions.visibilityOf(this.webElement),
this._elapsedTime,
`Element ${this.webElement.locator().toString()} is not present after ${this._elapsedTime}ms`);
)
}
(I'm giving you all my secret sauce ingredients haha) If you add this to onPrepare in the config
/**
* Set global environment configuration
*/
Object.defineProperty(global, '__stack', {
get: function() {
let orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack) {
return stack;
};
let err = new Error();
Error.captureStackTrace(err, arguments.callee);
let stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
},
});
// returns name of the file from which is called
Object.defineProperty(global, '__file', {
get: function() {
let path = __stack[1].getFileName();
try {
//*nix OSes
return path.match(/[^\/]+\/[^\/]+$/)[0];
} catch (error) {
//Windows based OSes
return path.match(/[^\\]+\\[^\\]+$/)[0];
}
},
});
// returns function name from which is called
Object.defineProperty(global, '__function', {
get: function() {
return __stack[1].getFunctionName();
},
});
// returns line number of the position in code when called
Object.defineProperty(global, '__line', {
get: function() {
return __stack[1].getLineNumber();
},
});
then you can use it for logging the file name, function name, and the line where it's called
For example,
async isVisible(){
await browser.wait(
ExpectedConditions.visibilityOf(this.webElement),
this._elapsedTime,
`Failed at ${__file} -> ${__function}() -> line ${__line}`
)
}
will result in this error
- Failed: Failed at common/index.js -> isVisible() -> line 82
Wait timed out after 1032ms
Wait timed out after 1032ms
So you can accommodate this to your needs
also I just realized you may want to play around with __stack variable itself

Solidity TypeError: artifacts is not a function

I am a student learning to write smart contracts using solidity. When running these codes using truffle(ganache):
Helloworld.sol
pragma solidity 0.5.12;
contract Helloworld {
string message = "Hello World";
function getMessage() public view returns (string memory) {
return message;
}
function setMessage(string memory newMessage) public payable {
message = newMessage;
}
}
Helloworld_migration.js
const Helloworld = artifacts.require("Helloworld");
module.exports = function(deployer, network, accounts){
deployer.deploy(Helloworld).then(function(instance){
instance.setMessage("Hello Again!", {value: 1000000, from: accounts[0]}).then(function(){
console.log("Success");
}).catch(function(err){
console.log("error: " + err);
});
}).catch(function(err){
console.log("Deploy failed " + err);
});
};
Helloworldtest.js
const Helloworld = artifacts().require("Helloworld");
contract("Helloworld", async function(){
it("should initialize correctly", async function(){
let instance = await Helloworld.deployed();
let message = await instance.getMessage();
assert(message === "Hello Again!");
});
});
I received this error msg:
TypeError: artifacts is not a function
at Object.<anonymous> (/Users/cherrybluemoon/projects/test/Helloworldtest.js:1:20)
at Module._compile (internal/modules/cjs/loader.js:1123:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1143:10)
at Module.load (internal/modules/cjs/loader.js:972:32)
at Function.Module._load (internal/modules/cjs/loader.js:872:14)
at Module.require (internal/modules/cjs/loader.js:1012:19)
at require (internal/modules/cjs/helpers.js:72:18)
at /usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:231:27
at Array.forEach (<anonymous>)
at Mocha.loadFiles
(/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:228:14)
at Mocha.run
(/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:536:10)
at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-
core/lib/test.js:135:1
at processTicksAndRejections (internal/process/task_queues.js:97:5)
You have to remove "()" from artifacts.
const Helloworld = artifacts.require("Helloworld");
Helloworld_migration.js is an invalid file name for a migration file. It needs to start with a number such as 1_migration.js or 1_helloworld_migration.js

Express error when running server.js

I am following these instructions to enable my angular app to be search engine friendly: https://github.com/angular/angular-cli/wiki/stories-universal-rendering
However when I run: node server.js, I get the following error:
$ node server.js /generic-skin/node_modules/angulartics2/dist/providers/ga/angulartics2-ga.js:1 (function (exports, require, module, __filename, __dirname) { import { Injectable } from '#angular/core';
^^^^^^ SyntaxError: Unexpected token import
at Object.exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.WRHe (/Users/Development/gambling-tec/skins/generic-skin/dist/server/main.bundle.js:1:220165)
at n (/skins/generic-skin/dist/server/main.bundle.js:1:211)
I am not 100% sure what this error means or how to go about bug testing it.
Any advice would be greatly appreciated.
EDIT
My server.js file
'use strict';
require('zone.js/dist/zone-node');
require('reflect-metadata');
const express = require('express');
const ngUniversal = require('#nguniversal/express-engine');
const { provideModuleMap } = require('#nguniversal/module-map-ngfactory-loader');
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist-server/main.bundle');
function angularRouter(req, res) {
res.render('index', {req, res});
}
const app = express();
app.engine('html', ngUniversal.ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', 'dist');
app.get('/', angularRouter);
app.use(express.static(`${__dirname}/dist`));
app.get('*', angularRouter);
app.listen(3000, () => {
console.log('Listening on port 3000');
});

wit.ai quickstart.js error from node, unexpected token{

I am going through the wit.ai quickstart tutorial and get an error from node (version 4.5.0 LTS), but I don't see the error in the code and also, it is the example code downloaded directly from wit.ai:
examples\quickstart.js:39
const {sessionId, context, entities} = request;
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3
Also, the code in the download from git is different than the code shown on the tutorial page:
Code from the git clone, example/quickstart.js is this:
'use strict';
let Wit = null;
let interactive = null;
try {
// if running from repo
Wit = require('../').Wit;
interactive = require('../').interactive;
} catch (e) {
Wit = require('node-wit').Wit;
interactive = require('node-wit').interactive;
}
const accessToken = (() => {
if (process.argv.length !== 3) {
console.log('usage: node examples/quickstart.js <wit-access-token>');
process.exit(1);
}
return process.argv[2];
})();
// Quickstart example
// See https://wit.ai/ar7hur/quickstart
const firstEntityValue = (entities, entity) => {
const val = entities && entities[entity] &&
Array.isArray(entities[entity]) &&
entities[entity].length > 0 &&
entities[entity][0].value
;
if (!val) {
return null;
}
return typeof val === 'object' ? val.value : val;
};
const actions = {
send(request, response) {
const {sessionId, context, entities} = request;
const {text, quickreplies} = response;
console.log('sending...', JSON.stringify(response));
},
getForecast({context, entities}) {
var location = firstEntityValue(entities, 'location');
if (location) {
context.forecast = 'sunny in ' + location; // we should call a weather API here
delete context.missingLocation;
} else {
context.missingLocation = true;
delete context.forecast;
}
return context;
},
};
const client = new Wit({accessToken, actions});
interactive(client);
but the tutorial says the const actions section should be this:
const actions = {
send(request, response) {
const {sessionId, context, entities} = request;
const {text, quickreplies} = response;
return new Promise(function(resolve, reject) {
console.log('sending...', JSON.stringify(response));
return resolve();
});
},
getForecast({context, entities}) {
return new Promise(function(resolve, reject) {
// Here should go the api call, e.g.:
// context.forecast = apiCall(context.loc)
context.forecast = 'sunny';
return resolve(context);
});
},
};
Regardless, both versions give the same error.
Turns out that, due to some ECMAScript 6 features in the code, if your node version <= 6.x.x, you have to add the flag harmony_destructuring to the node command line, as illustrated here:
node --harmony_destructuring examples/quickstart.js

Typescript can't find modules

I have an exported module in one file(upload.ts) in Typescript that I'm not able to import into another file(application.ts) without an error. Also, I'm not able to import ExpressJS.
Here's Upload.ts
/// <reference path="Main.d.ts" />
var fs = require('fs');
var path = require('path');
var formidable = require('formidable');
export class Upload{
public parse(req, res, next) {
...
}
public save(req, res, next) {
...
}
public respond(req, res, next) {
...
}
public errors(err, req, res, next) {
...
}
};
Here's application.ts
/// <reference path="Main.d.ts" />
var http = require("http");
import express = require("express");
import upload = require("Upload");
var upload = new upload.Upload();
var app = express.express();
var HOST = "localhost";
var PORT = 8080;
app.use(express.logger());
app.use(app.router);
The var app = express.express(); code throws an error: Unresolved function or method express. I've imported express.d.ts from https://github.com/borisyankov/DefinitelyTyped/tree/master/express
Here's the error:
module.js:340
throw err;
^
Error: Cannot find module 'upload'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:\Users\Me\WebstormProjects\untitled\server\main.js:12:14)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
Here's the header file, that references to both:
/// <reference path="upload.ts" />
/// <reference path="node.d.ts" />
/// <reference path="application.ts" />
/// <reference path="express.d.ts" />
You need to:
make sure to put both express.d.ts and node.d.ts into your project directory, near your application files
import them into your application
Example:
/// <reference path="libs/express.d.ts" />
/// <reference path="libs/node.d.ts" />
import http = require("http");
import express = require("express");
import upload = require("Upload");
var upload = new upload.Upload();
var app = express();
Upload module can be referenced in similar way.
BTW, your code looks more like javascript then typescript