|
| 1 | +/** |
| 2 | + * @description |
| 3 | + * HTTP code snippet generator for Kotlin using OkHttp. |
| 4 | + * |
| 5 | + * @author |
| 6 | + * @seanghay |
| 7 | + * |
| 8 | + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. |
| 9 | + */ |
| 10 | + |
| 11 | +'use strict' |
| 12 | + |
| 13 | +var CodeBuilder = require('../../helpers/code-builder') |
| 14 | + |
| 15 | +module.exports = function (source, options) { |
| 16 | + var opts = Object.assign({ |
| 17 | + indent: ' ' |
| 18 | + }, options) |
| 19 | + |
| 20 | + var code = new CodeBuilder(opts.indent) |
| 21 | + |
| 22 | + var methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'] |
| 23 | + |
| 24 | + var methodsWithBody = ['POST', 'PUT', 'DELETE', 'PATCH'] |
| 25 | + |
| 26 | + code.push('val client = OkHttpClient()') |
| 27 | + .blank() |
| 28 | + |
| 29 | + if (source.postData.text) { |
| 30 | + if (source.postData.boundary) { |
| 31 | + code.push('val mediaType = MediaType.parse("%s; boundary=%s")', source.postData.mimeType, source.postData.boundary) |
| 32 | + } else { |
| 33 | + code.push('val mediaType = MediaType.parse("%s")', source.postData.mimeType) |
| 34 | + } |
| 35 | + code.push('val body = RequestBody.create(mediaType, %s)', JSON.stringify(source.postData.text)) |
| 36 | + } |
| 37 | + |
| 38 | + code.push('val request = Request.Builder()') |
| 39 | + code.push(1, '.url("%s")', source.fullUrl) |
| 40 | + if (methods.indexOf(source.method.toUpperCase()) === -1) { |
| 41 | + if (source.postData.text) { |
| 42 | + code.push(1, '.method("%s", body)', source.method.toUpperCase()) |
| 43 | + } else { |
| 44 | + code.push(1, '.method("%s", null)', source.method.toUpperCase()) |
| 45 | + } |
| 46 | + } else if (methodsWithBody.indexOf(source.method.toUpperCase()) >= 0) { |
| 47 | + if (source.postData.text) { |
| 48 | + code.push(1, '.%s(body)', source.method.toLowerCase()) |
| 49 | + } else { |
| 50 | + code.push(1, '.%s(null)', source.method.toLowerCase()) |
| 51 | + } |
| 52 | + } else { |
| 53 | + code.push(1, '.%s()', source.method.toLowerCase()) |
| 54 | + } |
| 55 | + |
| 56 | + // Add headers, including the cookies |
| 57 | + var headers = Object.keys(source.allHeaders) |
| 58 | + |
| 59 | + // construct headers |
| 60 | + if (headers.length) { |
| 61 | + headers.forEach(function (key) { |
| 62 | + code.push(1, '.addHeader("%s", "%s")', key, source.allHeaders[key]) |
| 63 | + }) |
| 64 | + } |
| 65 | + |
| 66 | + code.push(1, '.build()') |
| 67 | + .blank() |
| 68 | + .push('val response = client.newCall(request).execute()') |
| 69 | + |
| 70 | + return code.join() |
| 71 | +} |
| 72 | + |
| 73 | +module.exports.info = { |
| 74 | + key: 'okhttp', |
| 75 | + title: 'OkHttp', |
| 76 | + link: 'http://square.github.io/okhttp/', |
| 77 | + description: 'An HTTP Request Client Library' |
| 78 | +} |
0 commit comments