1 /**
2 * Copyright © DiamondMVC 2016-2017
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.extensions.jsapi;
7 
8 mixin template extensions()
9 {
10   public import vibe.d : HTTPMethod;
11 
12   private static const string ajaxFormat = `
13     <script type="text/javascript">
14       function %s() {
15         var req = %s() || {
16           data: undefined,
17           dataType: 'json'
18         };
19 
20         req.url = '%s';
21 
22         $.ajax({
23           method: '%s',
24           data: req.data,
25           dataType: req.dataType,
26           contentType: req.dataType === 'json' ? 'application/json; charset=utf-8' : req.contentType,
27           url: window.location.protocol + '//' + window.location.host + (req.params ? (req.url + '?' + $.params(req.params)) : req.url),
28           success: function(result,status,xhr) {
29             %s({
30               result: result,
31               status: status,
32               xhr: xhr,
33               success: true
34             });
35           },
36           error: function(xhr,status,error) {
37             %s({
38                 xhr: xhr,
39                 status: status,
40                 error: error,
41                 success: false
42             });
43           }
44         });
45       }
46     </script>
47 `;
48 
49   /**
50   * Creates an ajax call function.
51   * Params:
52   *   method =            The method of the ajax call.
53   *   name =              The name of the call.
54   *   url =               The url of the call.
55   *   prepareFunction =   The function to call when preparing the request.
56   *   callbackFunction =  The function to call after the request has finished.
57   */
58   void ajax(HTTPMethod method, string name, string url, string prepareFunction, string callbackFunction)
59   {
60     import std.conv : to;
61     import std..string : format;
62 
63     append(ajaxFormat.format(name, prepareFunction, url, to!string(method), callbackFunction, callbackFunction));
64   }
65 }