Requiring "yargs" package in NodeJS - node.js

When running the below code in NodeJS
const yargs=require("yargs");
yargs.command({
command:"add",
describe:"add something",
builder:{
title:{
describe:"the title property",
demandOption:true,
type:"string"
},
body:{
describe:"damn",
demandOption:true,
type:"string"
}
},
handler:function(argv){
console.log(argv.title)
}
})
I get the below error
https://drive.google.com/file/d/13lmzJ23IRdNkAfbG1A2bhzRZvPQzhaqn/view
I have done everything the right way but still, it displays the error
"module not found".
How can I resolve the issue?

Related

AJV validation doesn't return multiple errors when different values are missing in the fastify request body

I have a fastify server with a post endpoint. It accepts a JSON request body with a validation. Server code below:
const fastify = require("fastify");
const server = fastify({
ajv: {
customOptions: {
allErrors: true,
},
},
logger: true,
});
const schema = {
schema: {
body: {
type: "object",
properties: {
data: {
type: "array",
items: {
type: "object",
properties: {
foo: {
type: "string",
},
bar: {
type: "string",
},
},
required: ["foo", "bar"],
},
},
},
required: ["data"],
},
},
};
server.post("/", schema, function (request, reply) {
console.log({
request: {
body: JSON.stringify(request.body),
},
});
reply.send({ message: "hello" });
});
server.listen(3000, function (err, address) {
if (err) {
fastify.log.error(err);
process.exit(1);
}
console.log(`server listening on ${address}`);
});
Below is a valid request body.
{ "data":[{ "bar": "bar exists", "foo": "foo exists" }]}
When I try to access the same server with multiple values in input missing i.e.,
{ "data":[{ "bar": "bar exists, foo missing" }, {}] }
I am getting the below response.
{
"statusCode": 400,
"error": "Bad Request",
"message": "body.data[0] should have required property 'foo', body.data[1] should have required property 'foo', body.data[1] should have required property 'bar'"
}
I want to get each error separately, instead of getting a single large error message as this request can go very large. I have tried a bit of trial around the ajv options but couldn't find anything.
Any help is appreciated. Cheers :)
You need to have a custom parser after the error is caught.
In order to achieve this approach, there is a method called setErrorHandler.
According to Fastify documentation:
Set a function that will be called whenever an error happens.
This is a simple parser, but you may need to change it to your taste:
server.setErrorHandler(function (error, request, reply) {
if (error.validation) {
reply.status(400).send({
statusCode: error.statusCode,
error: 'Bad Request',
message: error.validation.map(err => `${err.instancePath} ${err.message}`)
});
}
})
// rest of code

Encountering Unhandled error in Sanity on localhost

TypeError: Cannot read properties of null (reading 'jsonType')
at validateNonObjectFieldsProp (/static/js/app.bundle.js:169457:16)
at _default (/static/js/app.bundle.js:169425:155)
at visitors.reduce._objectSpread._problems (/static/js/app.bundle.js:167933:17)
at Array.reduce ()
at /static/js/app.bundle.js:167932:21
at /static/js/app.bundle.js:167951:70
at /static/js/app.bundle.js:168067:12
at /static/js/app.bundle.js:168082:95
at Array.forEach ()
at traverseSchema (/static/js/app.bundle.js:168081:9)
Showing the given error while performing the sanity start command, but it not showing on command line. While visiting the localhost website there's the error is showing this. I have tried downgrading the versions for sanity but still not solved this issue.
You missed type document in schema
Eg:
export default {
name: "user",
title: "User",
type: "document",
fields: [
{
name: "userName",
title: "UserName",
type: "string",
},
{
name: "image",
title: "Image",
type: "string",
},
],
};

Message extension sign-in not working properly

I have a message extension in the MS team, when I am trying to sign in it generates a pop-up with a validation code. I encountered this situation for the first time before that I just only need to enter the credentials.
const signInLink = await context.adapter.getSignInLink(context, this.connectionName);
return {
composeExtension: {
type: 'auth',
suggestedActions: {
actions: [{
type: 'openUrl',
value: signInLink,
title: 'MedxPlanner Authentication'
}]
}}
};
can you guide me where I am going wrong?
To implement authentication for messaging extension, you need to use below code snippet:
{
"composeExtension":{
"type":"auth",
"suggestedActions":{
"actions":[
{
"type": "openUrl",
"value": "{SignInLink}",
"title": "{Sign in to this app}"
}
]
}
}
}
Reference sample link:
https://github.com/microsoft/BotBuilder-Samples/tree/main/samples/csharp_dotnetcore/52.teams-messaging-extensions-search-auth-config

Swagger Nest.js ValidationPipe ApiBadRequestResponse

👋I just started playing around with Swagger and everything is amazing. I was able to document all API in an hour or so but I got stuck solving one last issue.
How can I tell swagger to show ApiBadRequestResponse in the format below?
#ApiOkResponse({
type: User,
})
#ApiBadRequestResponse({
type: {
error: String,
message: ValidationError[]
}
})
#Post('/signup')
signUp(
#Body(ValidationPipe) authCredentialsDto: CredentialsDTO
): Promise<User> {
return this.userService.signUp(authCredentialsDto)
}
From what I understand swagger doesn't know how to work with interfaces instead I have to use classes. Is there a simple way to document bad request response triggered by ValidationPipe. This is all native #nestjs behavior so I would assume there must be an easy solution.
This is what gets actually returned from API:
"statusCode": 400,
"error": "Bad Request",
"message": [
{
"target": {
"username": "somename",
"password": "****"
},
"value": "****",
"property": "password",
"children": [], // ValidationError[]
"constraints": {
"matches": "password too weak"
}
}
]

Mongoose Validation Error occurs on OpenShift but not local version

I am migrating my Node.js server with Mongoose to OpenShift and an error occurs on the live server that I cannot reproduce on my local WebStorm built-in server.
I get the error message:
undefined: {
properties: {
message: "Cannot read property 'options' of undefined"
type: "cast"
}-
message: "Cannot read property 'options' of undefined"
name: "ValidatorError"
kind: "cast"
}
This occurs when I try to push an element into the items array and save, for the following schema:
var listSchema = new mongoose.Schema({
owner: {type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
name: {type: String, required: true},
items: [
{
name:{
type: String,
required:true
},
quantity:Number,
check: Boolean
}
]
});
The local version that works, and the OpenShift version use the exact same code. The code that adds the new element is:
var listId = req.params["id"];
if (sessions.verifyToken(userId, token)) {
var data = req.body;
var query = List.findOne({
owner: userId,
"_id": listId
});
query.exec(function(err, list) {
...
//handle error and null (omitted for brevity)
...
list.items.push({ // error thrown here
name: req.body["name"],
quantity: req.body["quantity"],
check: false
});
list.save(function(err, list) {
if (err) {
var message = "Unable save appended list to persistent memory";
console.log(message, err);
res.setHeader("content-type", "application/json");
res.send(JSON.stringify({success: false, message: message, error: err}));
return;
}
res.setHeader("content-type", "application/json");
res.send(JSON.stringify(list));
});
});
I thought that maybe an earlier version of the schema had added a constraint, so I dropped the lists collection, but the problem did not go away.
What might be different on the OpenShift PaaS that could be causing the error?
[Edit]
Just for fun, I removed all required fields from items and now the error message is this:
"undefined": {
"properties": {
"message": "Cannot read property 'options' of undefined",
"type": "cast"
},
"message": "Cannot read property 'options' of undefined",
"name": "ValidatorError",
"kind": "cast"
},
"owner": {
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "owner"
},
"message": "Path `owner` is required.",
"name": "ValidatorError",
"kind": "required",
"path": "owner"
}
This seems to suggest that the Model loses its owner field somewhere between finding the list and saving it again.
[/Edit]
On OpenShift, when you find or findOne a model that has a required reference to another entity, that field will not be automatically filled in. Thus, when save is called, the field will be missing. Change
var query = List.findOne({
owner: userId,
"_id": listId
});
to
var query = List.findOne({
owner: userId,
"_id": listId
}).populate("owner");
For some reason, this does not work the same in every environment. For some, either it does automatically populate the reference field, or it assumed it unchanged when saving. I'm not sure which.

Resources