Skip to content

Commit

Permalink
feat(fetchText): add fetchText API for produce fetch for text response
Browse files Browse the repository at this point in the history
  • Loading branch information
r17x committed Oct 2, 2022
1 parent 1a82c51 commit a2636b2
Show file tree
Hide file tree
Showing 2 changed files with 116 additions and 41 deletions.
43 changes: 42 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,27 @@

</div>

<!-- vim-markdown-toc GFM -->

- [Usage](#usage)
- [Vite](#vite)
- [Example](#example)
- [Basic](#basic)
- [Nested](#nested)
- [API](#api)
- [Default](#default)
- [fetchText](#fetchtext)
- [Contributors](#contributors)
- [License](#license)

<!-- vim-markdown-toc -->

## Usage

Simply install and configure [`babel-plugin-macros`](https://github.com/kentcdodds/babel-plugin-macros) and then use `fetch.macro`.

> Some project that build with `create-react-app` doesn't need extra setup for `babel-plugin-macros`.
### Vite

To be able to use these macros in your [Vite](https://vitejs.dev/) project, you only need install [`vite-plugin-babel-macros`](https://github.com/itsMapleLeaf/vite-plugin-babel-macros) and add some configuration in `vite.config.js`. And it just work.
Expand All @@ -47,11 +64,13 @@ export default {
#### Basic

Run one of the following command inside your project directory to install the package:

```
$ npm i fetch.macro
or
$ yarn add fetch.macro
$ yarn add fetch.macro
```

Given the following `Input`:

```javascript
Expand Down Expand Up @@ -90,6 +109,28 @@ const fetchProject = ({ id, projectId, others, ...opts }) =>
fetch(`/api/v1/user/${id}/project/${projectId}/${others}`, opts);
```

## API

### Default

It will be produce a code for fetch function with URL by input and return response that need to be manual handle the response.

```
import f from 'fetch.macro'
const fetchByUrl = f("/api/v1/ping");
```

### fetchText

It will be produce a code for fetch function with URL by input and return [**response text**](https://webidl.spec.whatwg.org/#idl-USVString).

```
import { fetchText } from 'fetch.macro'
const fetchLicense = fetchText("https://raw.githubusercontent.com/r17x/fetch.macro/main/LICENSE");
```

## Contributors

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
Expand Down
114 changes: 74 additions & 40 deletions src/fetch.macro.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,55 +9,89 @@ const getValue = (path) =>

const isValueHaveArgs = (val) => /:\w+/g.test(val);

const memberExpressionTemplate = (ref) =>
({
[true]: "",
[ref === "default"]: "",
[ref === "fetchText"]: ".then(r => r.text())",
/**
* @todo
* - [ ] fetchJson
* - [ ] fetchBlob
* - [ ] fetchArrayBuffer
* - [ ] fetchFormData
*/
}.true);

module.exports = createMacro(
({
babel: { types: t, template },
references: {
default: paths,
// @TODO fetchText
fetchText,
/**
* @todo
* - [ ] fetchJson
* - [ ] fetchBlob
* - [ ] fetchArrayBuffer
* - [ ] fetchFormData
*/
},
}) => {
paths.forEach(({ parentPath }) => {
const value = getValue(parentPath);
const transform =
(reference) =>
({ parentPath }) => {
const value = getValue(parentPath);
const memberExpression = memberExpressionTemplate(reference);

if (value) {
if (isValueHaveArgs(value)) {
const buildFetch = template(`(PARAM) => fetch(URI, opts)`);
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(":", ""))),
),
}),
);
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 {
const buildFetch = template(`(opts) => fetch(URI, opts)`);
parentPath.replaceWithMultiple(
buildFetch({
URI: t.stringLiteral(value),
}),
);
parentPath.parentPath.remove();
}
} else {
parentPath.parentPath.remove();
}
});
};

(paths || []).forEach(transform("default"));
(fetchText || []).forEach(transform("fetchText"));
/**
* @todo
* - [ ] fetchJson
* - [ ] fetchBlob
* - [ ] fetchArrayBuffer
* - [ ] fetchFormData
*/
},
);

0 comments on commit a2636b2

Please sign in to comment.