I am new to nodejs and I am trying to export my custom module but it says function is not defined or is not a function.
I have created a module which contains a function to validate the request body using Joi library. Below is what I have done
validator.js
const Joi = require('joi');
var validateCustomer = function(customer) {
const schema = {
name: Joi.string().min(3).required()
}
return Joi.validate(customer, schema)
}
module.exports.validator = validateCustomer;
customers.js
const validator = require('../myModules/validator');
router.post('/', async (req, res) => {
const {error} = validator(req.body);
if(error) return res.error(404).send(error.details[0].message);
...some code
});
Please help
Change out
module.exports.validator = validateCustomer;
for
module.exports = validateCustomer
in validator.js.
Related
Using node + express. I want to create a module that use several querys.
how can I export this asynchronous function to app.js?
This is the function that im trying to make it work:
app.js (where io are socketio instance)
const users = require('./sockets/users')(io)
users.js
const Users = require('../models/Users.model')
const users = async function(client){
client.on('connection', socket =>{
socket.on('userAdd',(data) =>{
console.log(data);
})
const users = await Users.find()
console.log(users[0]);
})
}
module.exports = users
Error: SyntaxError: await is only valid in async function
First create two files. you can create functions into one and can export it and in another file you can import that functions. check the code below.
> server.js
const addition = require('./addition.js') // path to your another file
const result = addition.add(5, 8) // calling function of another file
console.log(result)
another file
> addition.js
const add = (x, y) => x + y;
module.exports = { add } // export this function
output:
13
I was typing the async keyword in the incorrect function. Its in the connection function
const Users = require('../models/Users.model')
const users = function(client){
client.on('connection', async socket =>{
socket.on('userAdd',(data) =>{
console.log(data);
})
const users = await Users.find()
console.log(users[0]); //user 1
})
}
module.exports = users
You can try to use a class for that and export that class and use it
JS newbie here. I am using Jasmine to test a NodeJS application which uses MongoDB and Mongoose, and I would like to replace my static test fixtures with dynamic factories. https://github.com/ratson/factory-bot looks good to me.
However, all of the examples are from a single file and don't demonstrate exporting/importing between files, so I don't understand what to modules.exports = in order to use a factory in my specs.
I'm also using ES5 if that matters.
My question is: how do I export this definition?
spec/factories/user.js
const factory = require('factory-bot').factory;
factory.setAdapter(new FactoryBot.MongooseAdapter());
const User = require('../models/user');
factory.define('user', User, {
username: 'Bob',
expired: false
});
factory.extend('user', 'expiredUser', {
expired: true
});
And then how do I use my export so that I can make sampleUsers?
spec/controllers/user.js
const reqs = require("../support/require")
describe("GET /users", () => {
describe("index", () => {
var data = {};
var sampleUsers = factory.createMany('user', 5);
beforeEach((done) => {
reqs.Request.get(/users", (error, response, body) => {
data.status = response.statusCode;
data.body = JSON.parse(body);
done();
});
});
it("returns a 200 response status", () => {
expect(data.status).toBe(200);
});
it("responds with the users collection", async () => {
expect(data.body.users).toBe(sampleUsers);
});
});
});
Thanks in advance for any advice.
You just need to require your factory definitions before using them.
Here's an example of what you could do:
spec/factories/user.js
const { factory } = require('factory-bot');
const User = require('../models/user');
factory.setAdapter(new FactoryBot.MongooseAdapter());
factory.define('user', User, {
username: 'Bob',
expired: false
});
factory.extend('user', 'expiredUser', {
expired: true
});
spec/factories/index.js:
const { factory } = require("factory-bot");
// Require factories to use with the exported object
require("./user.js");
module.exports = factory;
spec/controllers/user.js:
const factory = require("../../factories");
...
const sampleUsers = factory.createMany('user', 5);
The key difference between the example above and your sample code is the index.js file which requires factory-bot and all the factory definitions. By requiring the definitions, you will be able to use them.
If you require('factory-bot') directly instead of require('spec/factories'), you will need to require the factory definitions you want to use.
I am trying to access Tron smart contract which is deployed on the Shasta test network using Tron-Web. I am using node-casiko server Following is my code:
const TronWeb = require('tronweb')
// This provider is optional, you can just use a url for the nodes instead
const HttpProvider = TronWeb.providers.HttpProvider;
const fullNode = 'https://api.shasta.trongrid.io';
const solidityNode = 'https://api.shasta.trongrid.io';
const eventServer = 'https://api.shasta.trongrid.io';
const privateKey = 'my test account private key';
const tronWeb = new TronWeb(
fullNode,
solidityNode,
eventServer,
privateKey
);
module.exports = {
tmp: async function (req, res, next){
try{
var contract = await tronWeb.trx.getContract("TS71i14jzLawbtu4qPDKEsFERSp6CQb93948");
//res.send(contract)
var result = await contract.test().call();
//res.send(result);
}
catch(err){
console.error(err)
}
}
}
When I execute this js file using node having version v10.15.3. I am getting Error as:
TypeError: contract.test is not a function
at tmp (/home/administrator/node-Casiko/models/tronContract.js:25:32)
at process._tickCallback (internal/process/next_tick.js:68:7)
If I print the contract variable it is printing all information about the contract, but it is not calling the contract methods. Can somebody help me with this problem?
Well, I managed to find an answer for self-question. Just change the code as below. It works!!
module.exports = {
tmp: async function (req, res, next){
try{
var contract = await tronWeb.contract()
.at("TS71i14jzLawbtu4qPDKEsFERSp6CQb93948")
var result = await contract.test().call();
}
catch(err){
console.error(err)
}
}
I'm trying fastify with fastify-bookshelfjs.
contact (model)
module.exports = async function (fastify) {
console.log("4")
fastify.bookshelf.Model.extend({
tableName: 'contacts',
})
}
contact (controller)
console.log("3")
const Contact = require('../models/contact')()
// Get all contact
async function getContact(req, reply) {
const contacts = Contact.fetchAll()
reply.code(200).send(contacts)
}
module.exports = getContact
contact (routes)
module.exports = async function (fastify) {
console.log("2")
const contact = require('../controller/contact')
fastify.get('/', contact.getContact)
}
When the server start I get this output
2
3
4
(node:10939) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'bookshelf' of undefined
1
server listening on 3000
Why fastify in contact(model) is undefined and how can fix ?
In your controller, when you import the model, you need to put fastify as argument.
Also, you have to import the fastify module.
Your contact (controller) should be
const fastify = require('fastify') // import the fastify module here
console.log("3")
const Contact = require('../models/contact')(fastify)
// Get all contact
async function getContact(req, reply) {
const contacts = Contact.fetchAll()
reply.code(200).send(contacts)
}
module.exports = getContact
I am currently trying to attach a global Mongoose on runtime with no luck. My plugin requires a few dependencies and options generated upon my app's bootstrapping thus I need to add it sequentially. Mongoose seems to ignore everything wrapped within a closure.
const mongoose = require('mongoose');
const config = {};
const {DB_CONNECT} = process.env;
const myPlugin = schema => {
console.log('done'); // this line is not logged at all
schema.methods.mymethod = () => {};
}
const connectAndAddPlugins = async () => {
await mongoose.connect(
DB_CONNECT,
{...config}
);
mongoose.plugin(myPlugin)
};
connectAndAddPlugins();
Any help will be highly appreciated.
Apparently, since a model gets compiled and loaded with Mongoose global plugins are not attached anymore thus models should get registered afterwards:
const mongoose = require('mongoose');
const config = {};
const {DB_CONNECT} = process.env;
const myPlugin = schema => {
console.log('done'); // this line is not logged at all
schema.methods.mymethod = () => {};
}
const connectAndAddPlugins = async () => {
await mongoose.connect(
DB_CONNECT,
{...config}
);
mongoose.plugin(myPlugin)
};
const loadModels = () => {
const model = mongoose.model('Cat', { name: String });
}
connectAndAddPlugins();
loadModels();