1 module mars.UrlHelper;
2 
3 import std.algorithm.searching;
4 import std.exception;
5 
6 version(unittest) {
7 	import std.stdio;
8 }
9 
10 import mars.RequestParams;
11 
12 class UrlHelper {
13 
14 	static string createUrl(string baseUrl, string requestUrl, string[string] urlParams, RequestParams params) {
15 		enforce(requestUrl !is null, new Exception("Cannot get request Url!"));
16 
17         string finalUrl;
18 
19 		if (requestUrl.startsWith("http")) {
20 			finalUrl = addArgsIfNeed(requestUrl, params);
21 		}
22 
23 		enforce(baseUrl !is null, new Exception("Cannot get base Url!"));
24 
25 		finalUrl = baseUrl ~ addArgsIfNeed(requestUrl, params);
26 
27 		if (urlParams !is null && urlParams.length > 0) {
28             finalUrl = setUrlParams(finalUrl, urlParams);
29 		}
30 
31 		return finalUrl;
32 	}
33 
34 	private static string setUrlParams(string url, string[string] urlParams) {
35 	    // TODO
36         return url;
37 	}
38 
39 	private static string addArgsIfNeed(string url, RequestParams params) {
40 		if (params is null || params.getParams.length == 0) {
41 			return url;
42 		}
43 
44 		import std.string;
45 		import std.algorithm.iteration;
46 
47 		string[string] args = params.getParams;
48 
49 		string urlParams = args.keys.map!(k => k ~ "=" ~ args[k]).join("&");
50 		if (canFind(url, "?")) {
51 			url = url ~ "&" ~ urlParams;
52 		} else {
53 			url = url ~ "?" ~ urlParams;
54 		}
55 
56 		return url;
57 	}
58 }
59 
60 unittest {
61 	try {
62 		UrlHelper.createUrl(null, null, null);
63 		assert(false);
64 	} catch (Exception e) {
65 		writeln(e.msg);
66 		assert(e !is null);
67 		assert(e.msg == "Cannot get request Url!");
68 	}
69 }