How to send array of strings in query parameters of get request in postman - get

I have postman mock server with collection, and one of the requests has parameter with type array.
Here is the definition for this query parameter in the API ymal file:
- name: departureAirports
required: false
in: query
explode: true
schema:
type: array
items:
type: string
pattern: ^[A-Z]{3}$
When I send this request from postman with value like this ["123"]
, I got this error:
The query parameter "departureAirports" needs to be of type array, but we found "["123"]"
So, How can I send array of strings in the query parameters in get request ?

You can send the value of parameter departureAirports array like
departureAirports[1]:1
departureAirports[2]:2
departureAirports[3]:3

Related

Filtering an array with a possible undefined value in prisma

]I'm currently using a GraphQL Api which I then use a resolver to fetch the data from the DB.
this is my graphql resolver
async getVideoPosts(
#Args({ name: 'keywords', type: () => [String], nullable: true }) keywords: string[]): Promise<VideoPost[]> {
const findVideoQuery = await this.prismaService.videoPost.findMany({
where: { keywords: {hasSome: keywords}}
})
And my usecase is this:
I'm trying to filter an array of videos, using keywords array, that if they exist, it will fetch all the records that contain some of the values (using hasSome filter) however, if I get undefined from graphql, it'll return all the records and not filter at all.
For some reason, if prisma gets undefined in the array filter it returns an error.
I've looked at the docs and it says that whenever a filter option gets undefined, it's as if it wasn't written and it'll ignore it.
This is what im getting when the keywords graphql argument is undefined:
Argument where.keywords of type StringNullableListFilter needs at least one argument. Available args are listed in green.
You can't pass undefined or null to hasSome. You will need to do some validation on keywords before you pass it.
I would be curious to read the docs you referenced.

Joi validation on multiple queries with Nest.js

I'm trying to validate a GET request on Nest.js that has multiple queries using Joi. I understand how to use UsePipes and validate a single object on a single param. However I now have an endpoint that has the multiple queries, here is my controller:
#Get(':cpId/search')
#UsePipes(new JoiValidationPipe(queryDTOSchema))
async getSomethingByFilters(
#Param('cpId') cpId: string,
#Query('startDate') startDate?: number,
#Query('endDate') endDate?: number,
#Query('el') el?: string,
#Query('fields') fields?: string,
#Query('keyword') keyword?: string,
#Query('page') page?: number,
#Query('limit') limit?: number,
)...
And UsePipes is now validating the same schema against each of the queries, and I don't understand how to validate each single query separately.
Is there a way to validate each query separately? I couldn't find any references and the only solution I can think of would be to transform all those queries into a single object, which is undesirable in this case.
You can pass a pipe as the second argument of a query-decorator:
#Query('startDate', new JoiValidationPipe(joi.number())) startDate?: number
But I personally would prefer validation as one query object, as it is easier to read and handle:
#Get(':corporatePartnerId/search')
async getEmployeesByFilters(
#Param('corporatePartnerId', new JoiValidationPipe(joi.string())) corporatePartnerId: string,
#Query(new JoiValidationPipe(QueryDtoSchema)) query: QueryDto,
)

How to check for empty object id in populate method?

I'm trying to populate array of objects using the following code:
inventory.populate(result, {
path: 'activities.mean',
$match: { 'activities.mean': {$ne: ''} }
}, callback);
where type of mean is:
mean:{type:String, ref: 'Inventory'}
While populating a result I get the error in my callback function:
CastError: Cast to ObjectId failed for value "" at path "_id" for model "Inventory"'...
Which clearly shows that I've results that contains empty activities.mean.
I tried different solutions provided including match that I wrote in above code but I can't really make it work. Not sure why match is not working here.
What I'm expecting this code to do is:
if activities.mean is empty string, then do not try to populate that mean.
More looks like that the issue is that you're using String type for a reference field – because of that mongoose is trying to cast string values to ObjectId which is normally used for references. It should be
mean: {
type: Schema.Types.ObjectId,
ref: 'Inventory'
}
Mongoose's documentation itself notes that
Note: ObjectId, Number, String, and Buffer are valid for use as refs. However, you should use ObjectId unless you are an advanced user and have a good reason for doing so.

Express/Swagger pre validation function for end points

I am working on express js with swagger.
I have created some end points with defining respective controller and function call.
tabs/users:
# binds a127 app logic to a route
x-swagger-router-controller: tabs
get:
description: Returns list of all users
# used as the method name of the controller
operationId: getUsers
parameters:
- name: name
in: query
description: name
required: false
type: string
responses:
"200":
description: Success
schema:
# a pointer to a definition
$ref: "#/definitions/TabResponse"
# responses may fall through to errors
default:
description: Error
schema:
$ref: "#/definitions/ErrorResponse"
Like oprtionId getUsers, I have multiple functions.
Inside controller tabs.js I have functions like
function getUser(){
//business logic
}
Now I have one use case for every call to my end points I need to validate the token which user sent with each request is valid or not.
For this, I need to add validation function call to each controller function.
But I am looking for the central solution so that every call should go through validation function.
Please suggest your thoughts on it.

Boolean selectors supplied as URL-embedded parameters do not work in Mongo+Express

Mongoose appears to ignore boolean selectors in a query string.
For example, I have a microservice for a blog that exposes API end-points like:
https://myservice.com/post/searchPost?postID=745&tree=true&visible=true
This search pulls out a post with the specified postID with all comments and sub-comments and ignoring those not marked for viewing.
The back-end has a Mongoose model wrapped around a MongoDB collection. I build a query string that I pass to the Mongoose find method, given that there are multiple URL-embedded querying parameters. The string looks like this:
var queryString = "{$and: [{postID: 745},{postParentIDList: 745},{postIsVisible: false}]}"
This works except that the boolean values are ignored. Note that the query works just fine.
Post.find({$and: [{postID: 745},{postParentIDList: 745},{postIsVisible: false}]}, callback(err, doc){// some code}); // A-OK!
The problem occurs only when the query is passed as as string.
Post.find(queryString, callback(err, doc){// some code}); // Boolean ignored
I have tried enclosing the boolean values in the query string in quotes, e.g. postIsVisible: 'false'. That hasn't resolved the issue. Another option is to replace boolean constraints with numeric 0/1. That would entail changing my data model which isn't practical at this point. Besides, it doesn't explain the observed behavior.
I am grateful for any help.
The Mongoose model (sample):
postIsVisible :{ // Attribute to support tomake only some post visible
type : Boolean,
required : true,
default : true,
},
postHeadline :{ //Headline of the Post, provided by user
type : String,
},
postDescription :{ //Decription of the Post, provided by user
type : String,
required : true,
},
And so on.

Resources