/
fetch.macro.js
124 lines (114 loc) · 3.64 KB
/
fetch.macro.js
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
const { createMacro } = require("babel-plugin-macros");
/**
* @typedef {[string, import('@babel/core').NodePath[]]} KeyValue
*/
/* import module name is defined in @var REFERENCES
* @example
* ```
* import { fetchText } from 'fetch.macro'
* ```
* */
const REFERENCES = [
"default",
"fetchText",
"fetchJson",
"fetchBlob",
"fetchFormData",
"fetchArrayBuffer",
"fetchClone",
];
/**
* @param {KeyValue} keyValue
* @return {boolean}
*/
const isAllowedReference = ([k, v]) => REFERENCES.includes(k) && Array.isArray(v) && v.length > 0;
/**
* This use for handle when value of fetch.macro have arguments
* e.g "/api/user/:id"
*
* @param {string} val
* @return {boolean}
*/
const isValueHaveArgs = (val) => /:\w+/g.test(val);
/**
* @param {import('@babel/core').NodePath} path
* @return {string?} value param when use with call expression or tagged template expression
*/
const getValue = (path) =>
({
[true]: () => null,
[path.isCallExpression()]: () => path.node.arguments[0].value,
[path.isTaggedTemplateExpression()]: () => path.node.quasi.quasis[0].value.cooked,
}).true();
/**
* @param {string} ref
* @return {string} property access at promise type data (e.g: .then .catch)
*/
const memberExpressionTemplate = (ref) =>
({
[true]: "",
[ref === REFERENCES[1]]: ".then(r => r.text())",
[ref === REFERENCES[2]]: ".then(r => r.json())",
[ref === REFERENCES[3]]: ".then(r => r.blob())",
[ref === REFERENCES[4]]: ".then(r => r.formData())",
[ref === REFERENCES[5]]: ".then(r => r.arrayBuffer())",
[ref === REFERENCES[6]]: ".then(r => r.clone())",
}).true;
/** @type { import('babel-plugin-macros').MacroHandler } */
const fetchMacro = ({ babel: { types: t, template }, references }) => {
/**
* @param {string} reference
* @return {(path: import('@babel/core').NodePath) => void}
*/
const transform =
(reference) =>
({ parentPath }) => {
const value = getValue(parentPath);
const memberExpression = memberExpressionTemplate(reference);
if (value) {
if (isValueHaveArgs(value)) {
const buildFetch = template(`(PARAM) => fetch(URI, opts)`.concat(memberExpression));
parentPath.replaceWithMultiple(
buildFetch({
PARAM: t.objectPattern(
value
.split("/")
.filter((v) => v.startsWith(":"))
.map((p) => {
const id = t.identifier(p.replace(":", ""));
return t.objectProperty(id, id, false, true);
})
.concat([t.restElement(t.identifier("opts"))]),
),
URI: t.templateLiteral(
value
.replace(/:\w+/g, "::::")
.split("::::")
.map((v, i, a) => t.templateElement({ raw: v, cooked: v }, i + 1 === a.length)),
value
.split("/")
.filter((v) => v.startsWith(":"))
.map((v) => t.identifier(v.replace(":", ""))),
),
}),
);
} else {
const buildFetch = template(`(opts) => fetch(URI, opts)`.concat(memberExpression));
parentPath.replaceWithMultiple(
buildFetch({
URI: t.stringLiteral(value),
}),
);
}
} else {
parentPath.parentPath.remove();
}
};
/**
* @param {KeyValue} keyValue
* @return {void}
*/
const transformByReference = ([k, v]) => v.forEach(transform(k));
Object.entries(references).filter(isAllowedReference).forEach(transformByReference);
};
module.exports = createMacro(fetchMacro);