Optional Url params in nestjs swagger - swagger

This is my code:
#Get('/get-presigned-url/:extension?')
async getS3PresignedUrl(#Param('extension') extension?: string): Promise<AwsTempPostUrlDto> {
return await this.aws.getTemporaryPostUrl(extension);
}
But the extension in the swagger is required.
How can I set url params as optional

I think you should use #Query instead of #Param

Related

How Can I validate the JSON body of an API call in a separate method

Trying to validate some JSON values outside of the first method. What would be the best way to do that in the second method ?
#When("^User sends API request with (.*) and no qualifiers and an State Code entry level T1.3$")
public void user_sends_API_request_with_no_qualifiers_and_an_entry_level_T(String path) {
response =
given()
.auth().oauth2(DomaniRx_RestAssuredOAuth2.access_token_code)
.queryParam("PhamacyID","12345")
.queryParam("Customer Set Type ID", "CustomerSetTypeValue")
.queryParam("PharmacyListIDShortName","Value")
.queryParam("DateFilled","04/17/2022")
.get(defaultURL+path)
.then()
.statusCode(200)
.extract().response();
}
#Then("^The Pharmacy ID in the response should match the (\\d+) in the request T1.3$")
public void the_Pharmacy_ID_in_the_response_should_match_the_in_the_request_T(String PharmacyID) {
}
I don't know the best way, but I think one way to achieve that is put response is an instance variable, then you can access it from other method in same class.
If you want to share response outside class, then use class (static) variable
You can assign your response body to a variable like the below:
Then you can make assertions easily on the other methods. You can define a ResponseModel according to your response. Its name can be changed. it's up to you.
private ResponseModel response;
.
response =
given()
.auth().oauth2(DomaniRx_RestAssuredOAuth2.access_token_code)
.queryParam("PhamacyID","12345")
.queryParam("Customer Set Type ID", "CustomerSetTypeValue")
.queryParam("PharmacyListIDShortName","Value")
.queryParam("DateFilled","04/17/2022")
.get(defaultURL+path)
.then()
.statusCode(200)
.extract().response()
.jsonPath().getObject(".", ResponseModel .class);

Swagger UI: how to hide Nest.js controller method argument input field?

I'm adding Swagger UI 4 to existing Nest.js 7 project.
There was #Headers decorator for the Nest.js controller method argument.
I added #ApiBearerAuth nest.js decorator for method.
#ApiBearerAuth('MyAuth')
#Get()
async getEmployees(
#Headers('Authorization')
auth: string,
#Query() query: EmployeesQuery,
) {
The result is that I have Authorization header input field and lock icon button in Swagger UI at the same time. Lock icon button authorization works. Authorization header input field doesn't work and Swagger UI requires to fill it (input value is actually ignored by Nest.js).
How can I make Swagger authorization field to become not required and hidden?
Found how to make not required:
#ApiBearerAuth('MyAuth')
#ApiParam({
name: 'Authorization',
required: false,
description:
'(Leave empty. Use lock icon on the top-right to authorize)',
})
#Get()
async getEmployees(
#Headers('Authorization') auth: string,
#Query() query: EmployeesQuery,
) {
An alternative could be to use #Req() instead of #Headers().
#Get()
async getEmployees(
#Req() req: Request,
#Query() query: EmployeesQuery,
): Promise<Employees[]> {
const token = req.headers.authorization;
.
.
.
Note: import the type Request from express.
import { Request } from 'express';
You can also create a custom decorator.
It's better than the first answer because you don't have to pass the entire request for testing and actually hide the header in opposite to the second answer.
const AuthorizationToken = createParamDecorator(
(data: string, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return request.headers.authorization;
},
);

custom OData v4 function always returns 406

So I'm trying to map this method as an Odata function ...
[HttpGet]
[EnableQuery]
public IHttpActionResult ForBuyerOrganisations([FromUri]int[] orgIds)
{
// this returns IQueryable<TRDetails>
// i tried throwing a ToList on there too to ensure it works and it does
var result = service.ForBuyerOrgs(orgIds);
return Ok(result);
}
I have mapped it like this ...
var forBuyers = Builder.EntityType<TRDetails>().Collection.Function("ForBuyerOrganisations");
forBuyers.ReturnsCollection<TRDetails>();
forBuyers.CollectionParameter<int>("orgIds");
... I also tried this ...
var forBuyers = Builder.EntityType<TRDetails>().Collection.Function("ForBuyerOrganisations");
forBuyers.ReturnsCollectionFromEntitySet<TRDetails>();
forBuyers.CollectionParameter<int>("orgIds");
I can call it with the url:
~/TRDetails/ForBuyerOrganisations?orgIds=1
The Problem:
The request executes my code and returns from this method, then the client gets a 406.
Any Ideas?
Yes. #Ouyang indicates the config error. Besides, as I seem, there are other four errors:
you should use [FromODataUri], not [FromUri] for the parameter.
you should call the function with namespace-qualified.
TRDetails/Namespace.ForBuyerOrganisations(...)
you should set the argument as list, because you config it as collection.
you should call the function using the () for parameter.
So, the following request is sample request:
~/TRDetails/Default.ForBuyerOrganisations(orgIds=[5,4,2,3,1])
If TRDetails is an entityset,
forBuyers.ReturnsCollectionFromEntitySet<TRDetails>("TRDetails");
I think you miss the entityset's name.

How do I get query parameters in the URL

In Dart I am working on a web game. In this I would need a function where I can get data from the URL, in the same way that you would get it in PHP. How would I do this?
Say I, for example, append the following to my URL when I load my web game: ?id=15&randomNumber=3.14. How can I get them in Dart either as a raw string (preferred) or in some other format?
You can use the Uri class from dart:core
https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.Uri
ie:
main() {
print(Uri.base.toString()); // http://localhost:8082/game.html?id=15&randomNumber=3.14
print(Uri.base.query); // id=15&randomNumber=3.14
print(Uri.base.queryParameters['randomNumber']); // 3.14
}
import 'dart:html';
void doWork(){
var uri = Uri.dataFromString(window.location.href); //converts string to a uri
Map<String, String> params = uri.queryParameters; // query parameters automatically populated
var param1 = params['param1']; // return value of parameter "param1" from uri
var param2 = params['param2'];
print(jsonEncode(params)); //can use returned parameters to encode as json
}
Import 'dart:html' then you can use window.location...

Dart Date String Formatting [duplicate]

Is there a function to do urlencoding in Dart? I am doing a AJAX call using XMLHttpRequest object and I need the url to be url encoded.
I did a search on dartlang.org, but it didn't turn up any results.
var uri = 'http://example.org/api?foo=some message';
var encoded = Uri.encodeFull(uri);
assert(encoded == 'http://example.org/api?foo=some%20message');
var decoded = Uri.decodeFull(encoded);
assert(uri == decoded);
http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html#ch03-uri
Update: There is now support for encode/decode URI in the Dart Uri class
Dart's URI code is placed in a separate library called dart:uri (so it can be shared between both dart:html and dart:io). It looks like it currently does not include a urlencode function so your best alternative, for now, is probably to use this Dart implementation of JavaScript's encodeUriComponent.
Uri.encodeComponent(url); // To encode url
Uri.decodeComponent(encodedUrl); // To decode url
I wrote this small function to convert a Map into a URL encoded string, which may be what you're looking for.
String encodeMap(Map data) {
return data.keys.map((key) => "${Uri.encodeComponent(key)}=${Uri.encodeComponent(data[key])}").join("&");
}
I dont' think there is yet. Check out http://unpythonic.blogspot.com/2011/11/oauth20-and-jsonp-with-dartin-web.html and the encodeComponent method.
Note, it's lacking some characters too, it needs to be expanded. Dart really should have this built in and easy to get to. It may have it in fact, but I didn't find it.
Safe Url Encoding in flutter
Ex.
String url = 'http://example.org/';
String postDataKey = "requestParam="
String postData = 'hdfhghdf+fdfbjdfjjndf'
In Case of get request :
Uri.encodeComponent(url+postDataKey+postData);
In Case of Post Data Request use flutter_inappwebview library
var data = postDataKey + Uri.encodeComponent(postData);
webViewController.postUrl(url: Uri.parse(url), postData: utf8.encode(data));
Uri.encodeComponent() is correct, Uri.encodeFull() has a bug, see below example:
void main() {
print('$text\n');
var coded = Uri.encodeFull(text);
print(coded);
print('\n');
coded = Uri.encodeComponent(text);
print(coded);
}
var text = '#2020-02-29T142022Z_1523651918_RC2EAF9OOHDB_RT.jpg';

Resources