|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +var util = require('util'); |
| 4 | + |
| 5 | +module.exports = function (options) { |
| 6 | + var opts = util._extend({ |
| 7 | + indent: ' ' |
| 8 | + }, options); |
| 9 | + |
| 10 | + var code = []; |
| 11 | + |
| 12 | + code.push('open Cohttp_lwt_unix'); |
| 13 | + code.push('open Lwt'); |
| 14 | + code.push(''); |
| 15 | + |
| 16 | + // Create URI |
| 17 | + code.push(util.format('let uri = Uri.of_string "%s" in', this.source.fullUrl)); |
| 18 | + |
| 19 | + // Add headers, including the cookies |
| 20 | + var headersPresent = this.source.headers && this.source.headers.length; |
| 21 | + var cookiesPresent = this.source.cookies && this.source.cookies.length; |
| 22 | + |
| 23 | + if (headersPresent || cookiesPresent) { |
| 24 | + code.push('let headers = Header.init ()'); |
| 25 | + |
| 26 | + if (headersPresent) { |
| 27 | + for (var header in this.source.headers) { |
| 28 | + code.push(util.format(opts.indent + '|> fun h -> Header.add h "%s" "%s"', this.source.headers[header].name, this.source.headers[header].value)); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + if (cookiesPresent) { |
| 33 | + var cookie = this.source.cookies.map(function(c){return c.name + '=' + c.value;}).join('; '); |
| 34 | + code.push(util.format(opts.indent + '|> fun h -> Header.add h "Cookie" "%s"', cookie)); |
| 35 | + } |
| 36 | + code.push('in'); |
| 37 | + } |
| 38 | + |
| 39 | + // Add body |
| 40 | + var bodyPresent = this.source.postData && this.source.postData.text; |
| 41 | + if (bodyPresent) { |
| 42 | + //Just text |
| 43 | + code.push(util.format('let body = %s in', JSON.stringify(this.source.postData.text))); |
| 44 | + } else if (this.source.postData && !this.source.postData.text && this.source.postData.params && this.source.postData.params.length) { |
| 45 | + // Post params |
| 46 | + bodyPresent = true; |
| 47 | + var body = this.source.postData.params.map(function(p){return p.name + '=' + p.value;}).join('&'); |
| 48 | + code.push(util.format('let body = "%s" in', body)); |
| 49 | + } |
| 50 | + |
| 51 | + // Do the request |
| 52 | + code.push(''); |
| 53 | + code.push(util.format('Client.call %s%s(Code.method_of_string "%s") uri', |
| 54 | + (headersPresent || cookiesPresent) ? "~headers " : "", |
| 55 | + bodyPresent ? "~body " : "", |
| 56 | + this.source.method |
| 57 | + )); |
| 58 | + |
| 59 | + // Catch result |
| 60 | + code.push('>>= fun (res, body_stream) ->'); |
| 61 | + code.push(opts.indent + '(* Do stuff with the result *)'); |
| 62 | + |
| 63 | + return code.join(opts.indent !== false ? ' \n' + opts.indent : ' '); |
| 64 | +}; |
| 65 | + |
| 66 | +module.exports.info = function () { |
| 67 | + return { |
| 68 | + key: 'ocaml', |
| 69 | + title: 'OCaml', |
| 70 | + link: 'https://github.com/mirage/ocaml-cohttp', |
| 71 | + description: 'Cohttp is a very lightweight HTTP server using Lwt or Async for OCaml', |
| 72 | + extname: '.ml' |
| 73 | + }; |
| 74 | +}; |
0 commit comments