๐Ÿ“ฆ Kong / httpsnippet

๐Ÿ“„ client.ts ยท 156 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156/**
 * @description
 * HTTP code snippet generator for R using httr
 *
 * @author
 * @gabrielakoreeda
 *
 * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
 */

export interface HttrOptions {
  /** @default '  ' */
  indent?: string;
}

import { CodeBuilder } from '../../../helpers/code-builder';
import { escapeForDoubleQuotes, escapeForSingleQuotes } from '../../../helpers/escape';
import { getHeader } from '../../../helpers/headers';
import { Client } from '../../targets';

export const httr: Client = {
  info: {
    key: 'httr',
    title: 'httr',
    link: 'https://cran.r-project.org/web/packages/httr/vignettes/quickstart.html',
    description: 'httr: Tools for Working with URLs and HTTP',
  },
  convert: ({ url, queryObj, queryString, postData, allHeaders, method }, options = {}) => {
    // Start snippet
    const { push, blank, join } = new CodeBuilder({
      indent: options.indent ?? '  ',
    });

    // Import httr
    push('library(httr)');
    blank();

    // Set URL
    push(`url <- "${url}"`);
    blank();

    // Construct query string
    const qs = queryObj;
    delete queryObj.key;

    const entries = Object.entries(qs);
    const entriesCount = entries.length;

    if (entriesCount === 1) {
      const entry = entries[0];
      push(`queryString <- list(${entry[0]} = "${entry[1]}")`);
      blank();
    } else if (entriesCount > 1) {
      push('queryString <- list(');

      entries.forEach(([key, value], i) => {
        const isLastItem = i !== entriesCount - 1;
        const maybeComma = isLastItem ? ',' : '';
        push(`${key} = "${value}"${maybeComma}`, 1);
      });

      push(')');
      blank();
    }

    // Construct payload
    const payload = JSON.stringify(postData.text);

    if (payload) {
      push(`payload <- ${payload}`);
      blank();
    }

    // Define encode
    if (postData.text || postData.jsonObj || postData.params) {
      switch (postData.mimeType) {
        case 'application/x-www-form-urlencoded':
          push('encode <- "form"');
          blank();
          break;

        case 'application/json':
          push('encode <- "json"');
          blank();
          break;

        case 'multipart/form-data':
          push('encode <- "multipart"');
          blank();
          break;

        default:
          push('encode <- "raw"');
          blank();
          break;
      }
    }

    // Construct headers
    const cookieHeader = getHeader(allHeaders, 'cookie');
    const acceptHeader = getHeader(allHeaders, 'accept');

    const setCookies = cookieHeader
      ? `set_cookies(\`${String(cookieHeader)
          .replace(/;/g, '", `')
          .replace(/` /g, '`')
          .replace(/[=]/g, '` = "')}")`
      : undefined;

    const setAccept = acceptHeader ? `accept("${escapeForDoubleQuotes(acceptHeader)}")` : undefined;

    const setContentType = `content_type("${escapeForDoubleQuotes(postData.mimeType)}")`;

    const otherHeaders = Object.entries(allHeaders)
      // These headers are all handled separately:
      .filter(([key]) => !['cookie', 'accept', 'content-type'].includes(key.toLowerCase()))
      .map(([key, value]) => `'${key}' = '${escapeForSingleQuotes(value)}'`)
      .join(', ');

    const setHeaders = otherHeaders ? `add_headers(${otherHeaders})` : undefined;

    // Construct request
    let request = `response <- VERB("${method}", url`;

    if (payload) {
      request += ', body = payload';
    }

    if (queryString.length) {
      request += ', query = queryString';
    }

    const headerAdditions = [setHeaders, setContentType, setAccept, setCookies]
      .filter(x => !!x)
      .join(', ');

    if (headerAdditions) {
      request += `, ${headerAdditions}`;
    }

    if (postData.text || postData.jsonObj || postData.params) {
      request += ', encode = encode';
    }

    request += ')';

    push(request);

    blank();
    // Print response
    push('content(response, "text")');

    return join();
  },
};