Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(codemod) : Conversion of Fetch API Calls to Ky #1261

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/codemods/fetch-to-ky/.codemodrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"$schema": "https://codemod-utils.s3.us-west-1.amazonaws.com/configuration_schema.json",
"name": "fetch-to-ky",
"version": "1.0.0",
"engine": "jscodeshift",
"private": false,
"arguments": [],
"meta": {
"tags": ["fetch-to-ky"],
"git": "https://github.com/codemod-com/codemod/tree/main/packages/codemods/fetch-to-ky"
}
}
2 changes: 2 additions & 0 deletions packages/codemods/fetch-to-ky/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
dist
9 changes: 9 additions & 0 deletions packages/codemods/fetch-to-ky/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2024 Codemod Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
82 changes: 82 additions & 0 deletions packages/codemods/fetch-to-ky/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
This codemod is designed to help you migrate your existing codebase from using the native `fetch` API to the more concise and convenient `ky` HTTP client library. By running this codemod, you can automatically update your code to leverage `ky`'s features, such as simpler syntax for common use cases like JSON requests and responses.

## Detailed Description

The codemod performs the following transformations:

- Replaces `fetch` calls with `ky` methods (`ky.get`, `ky.post`, `ky.put`, `ky.delete`).
- Simplifies request setup by using `ky`'s built-in methods for JSON handling (`.json()`).
- Removes manual error checking (`!resp.ok`), as `ky` automatically throws errors for non-2xx responses.
- Streamlines the code by reducing boilerplate and improving readability.

## Example

### Before

```ts
export async function getTodos() {
const resp = await fetch(`/todos`);
if (!resp.ok) throw resp;
return resp.json();
}

export async function addTodo(todo) {
const resp = await fetch(`/todo`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ todo }),
});
if (!resp.ok) throw resp;
return resp.json();
}

export async function updateTodo(todo) {
const resp = await fetch(`/todo/${todo.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ todo }),
});
if (!resp.ok) throw resp;
}

export async function deleteTodo(todoId) {
const resp = await fetch(`/todo/${todoId}`, {
method: 'DELETE',
});
if (!resp.ok) throw resp;
}
```

### After

```ts
import ky from 'ky';
export async function getTodos() {
const resp = await ky.get(`/todos`);
return resp.json();
}

export async function addTodo(todo) {
const resp = await ky.post(`/todo`, {
json: { todo },
});
return resp.json();
}

export async function updateTodo(todo) {
const resp = await ky.put(`/todo/${todo.id}`, {
json: { todo },
});
}

export async function deleteTodo(todoId) {
const resp = await ky.delete(`/todo/${todoId}`);
}

```

This codemod streamlines your existing fetch functions by converting them to use `ky`, eliminating unnecessary code, and making your HTTP requests more readable and maintainable.
35 changes: 35 additions & 0 deletions packages/codemods/fetch-to-ky/__testfixtures__/fixture1.input.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export async function getTodos() {
const resp = await fetch(`/todos`);
if (!resp.ok) throw resp;
return resp.json();
}

export async function addTodo(todo) {
const resp = await fetch(`/todo`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ todo }),
});
if (!resp.ok) throw resp;
return resp.json();
}

export async function updateTodo(todo) {
const resp = await fetch(`/todo/${todo.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ todo }),
});
if (!resp.ok) throw resp;
}

export async function deleteTodo(todoId) {
const resp = await fetch(`/todo/${todoId}`, {
method: 'DELETE',
});
if (!resp.ok) throw resp;
}
22 changes: 22 additions & 0 deletions packages/codemods/fetch-to-ky/__testfixtures__/fixture1.output.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import ky from "ky";
export async function getTodos() {
const resp = await ky.get(`/todos`);
return resp.json();
}

export async function addTodo(todo) {
const resp = await ky.post(`/todo`, {
json: { todo }
});
return resp.json();
}

export async function updateTodo(todo) {
const resp = await ky.put(`/todo/${todo.id}`, {
json: { todo }
});
}

export async function deleteTodo(todoId) {
const resp = await ky.delete(`/todo/${todoId}`);
}
19 changes: 19 additions & 0 deletions packages/codemods/fetch-to-ky/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "fetch-to-ky-conversion",
"license": "MIT",
"devDependencies": {
"@types/node": "20.9.0",
"typescript": "^5.2.2",
"vitest": "^1.0.1",
"@codemod.com/codemod-utils": "*",
"jscodeshift": "^0.15.1",
"@types/jscodeshift": "^0.11.10"
},
"scripts": {
"test": "vitest run",
"test:watch": "vitest watch"
},
"files": ["README.md", ".codemodrc.json", "/dist/index.cjs"],
"type": "module",
"author": "manishjha-04"
}
122 changes: 122 additions & 0 deletions packages/codemods/fetch-to-ky/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
export default function transform(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
let dirtyFlag = false;

// Check if `fetch` is used anywhere
const isFetchUsed =
root.find(j.CallExpression, { callee: { name: "fetch" } }).size() > 0;

// Add import statement for `ky` if `fetch` is used
if (isFetchUsed) {
const importStatement = j.importDeclaration(
[j.importDefaultSpecifier(j.identifier("ky"))],
j.literal("ky"),
);

// Insert the import statement at the top if not already present
if (!root.find(j.ImportDeclaration, { source: { value: "ky" } }).size()) {
root.get().node.program.body.unshift(importStatement);
dirtyFlag = true;
}
}

// Remove redundant response.ok checks
root.find(j.IfStatement).forEach((path) => {
const { test } = path.node;
if (
test.type === "UnaryExpression" &&
test.operator === "!" &&
test.argument.type === "MemberExpression" &&
test.argument.property.name === "ok" &&
test.argument.object.type === "Identifier"
) {
j(path).remove();
dirtyFlag = true;
}
});

// Replace fetch calls with ky
root.find(j.CallExpression, { callee: { name: "fetch" } }).forEach((path) => {
const url = path.node.arguments[0];
const options = path.node.arguments[1];
let method = "get";
let jsonBody = null;

if (options && j.ObjectExpression.check(options)) {
const methodProperty = options.properties.find(
(prop) => prop.key.name === "method",
);
if (methodProperty && j.Literal.check(methodProperty.value)) {
method = methodProperty.value.value.toLowerCase();
}

const bodyProperty = options.properties.find(
(prop) => prop.key.name === "body",
);
if (
bodyProperty &&
j.CallExpression.check(bodyProperty.value) &&
bodyProperty.value.callee.object.name === "JSON" &&
bodyProperty.value.callee.property.name === "stringify"
) {
jsonBody = bodyProperty.value.arguments[0];
}
}

const kyCall = j.callExpression(
j.memberExpression(j.identifier("ky"), j.identifier(method)),
jsonBody
? [
url,
j.objectExpression([
j.property.from({
kind: "init",
key: j.identifier("json"),
value: jsonBody,
}),
]),
]
: [url],
);

// Replace the fetch call with ky() but don't append .json() immediately
path.replace(kyCall);
dirtyFlag = true;
});

// Ensure .json() is only appended when response is not already handled
root.find(j.VariableDeclaration).forEach((path) => {
path.node.declarations.forEach((declarator) => {
if (
j.CallExpression.check(declarator.init) &&
declarator.init.callee.type === "MemberExpression" &&
declarator.init.callee.object.name === "ky"
) {
const varName = declarator.id.name;

// Look for subsequent .json() calls and prevent duplicate calls
const hasJsonCall =
root
.find(j.CallExpression, {
callee: {
object: { name: varName },
property: { name: "json" },
},
})
.size() > 0;

if (!hasJsonCall) {
declarator.init = j.awaitExpression(
j.callExpression(
j.memberExpression(declarator.init, j.identifier("json")),
[],
),
);
}
}
});
});

return dirtyFlag ? root.toSource() : undefined;
}
48 changes: 48 additions & 0 deletions packages/codemods/fetch-to-ky/test/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import assert from "node:assert";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import jscodeshift, { type API } from "jscodeshift";
import { describe, it } from "vitest";
import transform from "../src/index.js";

const buildApi = (parser: string | undefined): API => ({
j: parser ? jscodeshift.withParser(parser) : jscodeshift,
jscodeshift: parser ? jscodeshift.withParser(parser) : jscodeshift,
stats: () => {
console.error(
"The stats function was called, which is not supported on purpose",
);
},
report: () => {
console.error(
"The report function was called, which is not supported on purpose",
);
},
});

describe("fetch-to-ky-conversion", () => {
it("test #1", async () => {
const INPUT = await readFile(
join(__dirname, "..", "__testfixtures__/fixture1.input.ts"),
"utf-8",
);
const OUTPUT = await readFile(
join(__dirname, "..", "__testfixtures__/fixture1.output.ts"),
"utf-8",
);

const actualOutput = transform(
{
path: "index.js",
source: INPUT,
},
buildApi("tsx"),
{},
);

assert.deepEqual(
actualOutput?.replace(/W/gm, ""),
OUTPUT.replace(/W/gm, ""),
);
});
});
35 changes: 35 additions & 0 deletions packages/codemods/fetch-to-ky/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"compilerOptions": {
"module": "NodeNext",
"target": "ESNext",
"moduleResolution": "NodeNext",
"lib": ["ESNext", "DOM"],
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"jsx": "react-jsx",
"useDefineForClassFields": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"preserveWatchOutput": true,
"strict": true,
"strictNullChecks": true,
"incremental": true,
"noUncheckedIndexedAccess": true,
"noPropertyAccessFromIndexSignature": false,
"allowJs": true
},
"include": [
"./src/**/*.ts",
"./src/**/*.js",
"./test/**/*.ts",
"./test/**/*.js"
],
"exclude": ["node_modules", "./dist/**/*"],
"ts-node": {
"transpileOnly": true
}
}
Loading
Loading