1 /** 2 * Copyright © DiamondMVC 2019 3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE) 4 * Author: Jacob Jensen (bausshf) 5 */ 6 module diamond.http.remote; 7 8 import vibe.d : HTTPClientRequest, HTTPClientResponse, requestHTTP, HTTPMethod; 9 10 import diamond.http.method; 11 12 /** 13 * Creates a remote request. 14 * Params: 15 * url = The url of the resource. 16 * method = The http method of the request. 17 * responser = Handler for managing the response of the resource. 18 * requester = Handler for setting up custom request configurations. 19 */ 20 void remoteRequest 21 ( 22 string url, 23 HttpMethod method, 24 scope void delegate(scope HTTPClientResponse) responder = null, 25 scope void delegate(scope HTTPClientRequest) requester = null, 26 ) 27 { 28 return requestHTTP 29 ( 30 url, 31 (scope request) 32 { 33 request.method = cast(HTTPMethod)method; 34 35 if (requester !is null) 36 { 37 requester(request); 38 } 39 }, 40 (scope response) 41 { 42 if (responder !is null) 43 { 44 responder(response); 45 } 46 } 47 ); 48 } 49 50 /** 51 * Creates a remote json request. 52 * Params: 53 * url = The url of the resource. 54 * method = The http method of the request. 55 * responser = Handler for managing the json response. 56 * requester = Handler for setting up custom request configurations. 57 */ 58 void remoteJson(T, CTORARGS...) 59 ( 60 string url, 61 HttpMethod method, 62 scope void delegate(T) responder, 63 scope void delegate(scope HTTPClientRequest) requester, 64 CTORARGS args 65 ) 66 { 67 return fetchRemote 68 ( 69 url, method, 70 (scope response) 71 { 72 import vibe.data.json; 73 74 static if (is(T == struct)) 75 { 76 T value; 77 78 value.deserializeJson(json); 79 80 responder(value); 81 } 82 else static if (is(T == class)) 83 { 84 auto value = new T(args); 85 86 value.deserializeJson(json); 87 88 responder(value); 89 } 90 else 91 { 92 static assert(0); 93 } 94 }, 95 requester 96 ); 97 }