How can nestjs recognize two path? - nestjs

I have created the following two APIs.
However, when I hit "http://localhost:3000/arg1/arg2", it is recognized, but
But "http://localhost:3000/show/config" is not recognized.
How can I make "show/config" URL Mapping?
#Get(':arg1/:arg2')
pathMappingTest(): string {
return 'pathMappingTest';
}
#Get('show/config')
showConfig(): string {
return this.appService.showConfig();
}

try set :arg/:otherArg for the last, because if you put anything with two arg with slash between, the API will know it is two args.
#Get('show/config')
showConfig(): string {
return this.appService.showConfig();
}
#Get(':arg1/:arg2')
pathMappingTest(): string {
return 'pathMappingTest';
}

Related

Is there a regex to be able to match two url's , one that has a wildcard and one that doesn't?

I am writing a program in Nodejs with the following scenarios.
I have an array of url's that include wildcards, such as the following:
https://*.example.com/example/login
http://www.example2.com/*/example2/callback
Secondly, I have an incoming redirect url that I need to validate matches what is in the array of url's above. I was wondering if there was a way using Regex or anything else that I can use something like arr.includes(incomingRedirectUrl) and compare the two.
I can match non-wildcard url's using array.includes(incomingRedirectUrl), but when it comes to matching the array that has wildcards, I cannot think of a solution.
For example,
https://x.example.com/example/login should work because it matches the first url in the above example, only replacing the "*" with the x.
Is there a way I can achieve this? Or do I have to break down the url's using something like slice at the "*" to compare the two?
Thanks in advance for any help.
for (let i = 0; i < arr.length; i++) {
if (arr[i].indexOf('*') !== -1) {
wildcardArr.push(arr[i]);
} else {
noWildcardArr.push(arr[i]);
}
}
***Note, the reason I check noWildcardArr first is because most of the validate redirect url's do not contain wildcard
if (noWildcardArr.includes(incomingRedirectUrl)) {
//Validated correct url, proceed with the next part of my code (this part already works)
} else if (wildcardArr.includes(incomingRedirectUrl)) {
//need to figure out this logic here, not sure if the above is possible without formatting wildcardArr but url should be validated if url matches with wildcard
} else {
log.error('authorize: Bad Request - Invalid Redirect URL');
context.res = {
status: 400,
body: 'Bad Request - Invalid Redirect URL',
};
}
You could compile your URL array into proper regex and then iterate over them to see if it matches. Similar to something like a web framework would do that allows URL path parameters such as /users/:id.
function makeMatcher(urls) {
const compiled = urls.map(url => {
// regex escape the url but dont escape *
let exp = url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, '\\$&');
// replace * with .+ for the wildcard
exp = exp.replaceAll('*', '.+');
// the expression is used to create the match function
return new RegExp(`^${exp}$`);
});
// return the match function, which returns true, on the first match,
// or false, if there is no match at all
return function match(url) {
return compiled.find(regex => url.match(regex)) == undefined ?
false :
true;
};
}
const matches = makeMatcher([
'https://*.example.com/example/login',
'http://www.example2.com/*/example2/callback'
]);
// these 2 should match
console.log(matches('https://x.example.com/example/login'));
console.log(matches('http://www.example2.com/foo/example2/callback'));
// this one not
console.log(matches('http://nope.example2.com/foo/example2/callback'));

Typescript Array.filter empty return

Problem statement
I've got problem with an object array I would like to get a sub object array from based on a object property. But via the Array.filter(lambda{}) all I get is an empty list.
The object is like:
export interface objectType1 {
someName: number;
someOtherName: string;
}
export interface ObjectType2 {
name: string;
other: string;
ObjectType1: [];
}
The method to get the subArray is:
private getSubArray(toDivied: ObjectType2[], propertyValue: string){
let list: ObjectType2[] = toDivied.filter((row:ObjectType2) => {
row.name === propertyValue
});
return list;
}
Analys
Namely two things been done ensure filter comparing works and that the data is "as expected".
Brekepoints in visual studio code
Via break points in the return and filter compareison I've inspected that the property value exists (by conditions on the break point) and that the "list" which is returned is empty.
I would like to point out that I use a Typescript linter which usally gives warning for the wrong types and undefined variable calls and such so I am quite sure it shouldn't be an syntax problem.
Tested via javascript if it works in chrome console
remove braces inside callback function
private getSubArray(toDivied: ObjectType2[], propertyValue: string){
let list: ObjectType2[] = toDivied.filter((row:ObjectType2) =>
row.name === propertyValue
);
return list;
}

String.Replace for Path and Url

I have a problem about path string data. I have a string columb in Database and keep path in this columb.Like this;
D:\SCANNEDDOCUMENTS\2\3C9DED0628F44190ABF92D3C14F14A14-2-D.pdf
In my project i'll reach documents on IIS.I config all settings for IIS. And I need an Url like this;
HTTP://LOCALHOST/SCANNEDDOCUMENTS/2/3C9DED0628F44190ABF92D3C14F14A14-2-D.pdf
And i don't want to change paths in database.They're original local path.Only i need change on viewmodel. So need replace first path to second Url. And when i get path value from database i saw that:
D:\\SCANNEDDOCUMENTS\\2\\3C9DED0628F44190ABF92D3C14F14A14-2-D.pdf
There is double backslash? Why? And how can replace this like my wanted Url?
I tried several thing like;
private static string ReplaceDocumentPathLocalToWeb(string path)
{
if (!string.IsNullOrEmpty(path))
{
SArchiveModule archivingModule = ContainerManager.Container.GetInstance<SArchiveModule>();
SbtGeneralParameterModel parameter = archivingModule.GetGeneralParameters();
string docDirectory = parameter.DocumentDirectoryPath;
string docWebDirectory = parameter.DocumentWebRootPath + #"/" + parameter.DocumentWebFolderPath;
path.Replace(docDirectory, docWebDirectory);
path.Replace("\"", "/");
if (path.StartsWith(#"/"))
{
path.TrimStart(new char[] { '/' });
}
if (path.EndsWith(#"/"))
{
path.TrimEnd(new char[] { '/' });
}
}
return path;
}
path="D:\SCANNEDDOCUMENTS\2\3C9DED0628F44190ABF92D3C14F14A14-2-D.pdf";
parameters from database too;
docDirectory="D:\SCANNEDDOCUMENTS"
docWebDirectory="HTTP://LOCALHOST/SCANNEDDOCUMENTS"
But this code is not working too:
path.Replace(docDirectory, docWebDirectory);
What should i do for replace? And why my data came with double backslash? In database it's with one backslash?
So sorry my wrong. Now i got the problem. I couldn't see the string.replace result 'cause i need use code like:
path=path.Replace(docDirectory, docWebDirectory);
path=path.Replace("\"", "/");
if (path.StartsWith(#"/"))
{
path=path.TrimStart(new char[] { '/' });
}
if (path.EndsWith(#"/"))
{
path=enter code here`path.TrimEnd(new char[] { '/' });
}
It's really silly mistake...

PHP-like string parsing

I'm writing a mini-console of sorts and I'm trying to figure out how to extract things from a link. For example, in PHP this is a request variable
so:
http://somelink.com/somephp.php?variable1=10&variable2=20
Then PHP figures out the url parameters and assigns them to a variable.
How would I parse something like this in Swift?
So, given the string I'd want to take: variable1=10 and variable2=20 etc, is there a simple way to do this? I tried googling around but didn't really know what I was searching for.
I have a really horrible hacky way of doing this but it's not really extendable.
You’d be wanting NSURLComponents:
import Foundation
let urlStr = "http://somelink.com/somephp.php?variable1=10&variable2=20"
let components = NSURLComponents(string: urlStr)
components?.queryItems?.first?.name // Optional("variable1")
components?.queryItems?.first?.value // Optional("10")
You might find it helpful to add a subscript operator for the query items:
extension NSURLComponents {
subscript(queryItemName: String) -> String? {
// of course, if you do this a lot,
// cache it in a dictionary instead
for item in self.queryItems ?? [] {
if item.name == queryItemName {
return item.value
}
}
return nil
}
}
if let components = NSURLComponents(string: urlStr) {
components["variable1"] ?? "No value"
}

Compare enum without considering its arguments

Let me make this clear, I have this enum:
enum Token {
Number(v:Float);
Identifier(v:String);
TString(v:String);
Var;
Assign;
Division;
// and so on
}
I want to check if the value of a variable is an Identifier, but this doesn't work:
if(tk == Token.Identifier) {
It only allows me to compare the values if I pass arguments:
if(tk == Token.Identifier('test')) {
But this will only match if the identifier is 'test', but I want to match any identifier.
Type.enumConstructor(tk) == "Identifier"
Read the Type doc for more methods on enum.
Update (2019-02-04):
At the time of writing this answer it was still Haxe 2.06. Much have changed since then.
At this moment, for Haxe 3 (or 4), I would recommend pattern matching, specifically using single pattern check instead:
if (tk.match(Identifier(_)) ...
which is a short hand for
if (switch tk { case Identifier(_): true; case _: false; }) ...
_ is the wildcard that matches anything.
alternatively:
static function isIdentifier(token : Token) return switch(token) { case Token.Identifier(_): true; default: false; }
Using "using" you should also be able to do:
if(tk.isIdentifier()) {
Or even:
tk.match(Token.Identifier(_));

Resources