acacode / acacode/swagger-typescript-api

Fix: Response object mutation fails in ESM environments with node-fetch v3

Đang mở
#1,429 0 bình luận 0 reaction 0 người được giao Xem trên GitHub
bug
Ngôn ngữ chính
TypeScript
Star
4.1k
Fork
436
Chỉ số merge pull request
Không có pull request nào được merge trong 30 ngày

Mô tả

## Problem
The generated Fetch client attempts to directly mutate the Response object by adding `data` and `error` properties. This fails in ESM environments using node-fetch v3 because Response objects are read-only.

## Error
```
TypeError: Cannot set property data of # which has only a getter
at /node_modules/.pnpm/@oars+roleauth-api@1.0.53765/node_modules/@oars/v1.ts:1237:13
```

## Environment
- Node.js with ESM modules (`"type": "module"` in package.json)
- node-fetch v3.x (ESM-only version)
- swagger-typescript-api v13.0.23 (also confirmed in v13.2.13)

## Root Cause
In `templates/base/http-clients/fetch-http-client.ejs` (lines 187-189), the code attempts to directly mutate the Response object:

```javascript
const r = response as HttpResponse;
r.data = (null as unknown) as T;
r.error = (null as unknown) as E;
```

This works in CommonJS environments but fails in ESM with node-fetch v3 where Response objects are truly read-only and cannot have new properties added.

## Impact
Anyone migrating to ESM modules or using node-fetch v3 cannot use the generated Fetch client without workarounds.

## Current Workaround
Users must wrap fetch with a Proxy to make Response properties writable:

```javascript
const wrappedFetch = async (...args) => {
const response = await fetch(...args);
return new Proxy(response, {
set(target, prop, value) {
if (prop === 'data' || prop === 'error') {
target[prop] = value;
return true;
}
return Reflect.set(target, prop, value);
},
get(target, prop) {
if (prop === 'data' || prop === 'error') {
return target[prop];
}
const value = target[prop];
if (typeof value === 'function') {
return value.bind(target);
}
return value;
}
});
};
```

## Proposed Solution
Create a wrapper object instead of mutating the Response directly. This maintains backward compatibility while supporting modern ESM environments.

I'll be submitting a PR with a fix shortly.

Hướng dẫn đóng góp

Chưa lập chỉ mục được hướng dẫn đóng góp cho kho mã nguồn này

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.