Skip to content

Commit

Permalink
fetch polyfill and better package.json
Browse files Browse the repository at this point in the history
  • Loading branch information
insyri committed Oct 23, 2022
1 parent de2635b commit bf87041
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 24 deletions.
10 changes: 10 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@
* );
* ```
*
* ## `fetch` API in Node.js
*
* Node.js v18 has a native browser-like fetch interface. Versions
* below are normally using [`node-fetch`](https://github.com/node-fetch/node-fetch)
* to circumvent this issue.
*
* For environments using Node v18 and earlier, Tpy uses the native
* fetch without requiring the package. Environments containing earlier
* versions of Node will require the package.
*
* @module
*/

Expand Down
15 changes: 9 additions & 6 deletions node/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tpy",
"version": "v1.0.0-pre-release-4",
"version": "v1.0.0-pre-release-5",
"description": "🔑 A strongly typed Pylon API client.",
"license": "MIT",
"type": "commonjs",
Expand Down Expand Up @@ -30,14 +30,17 @@
"bugs": {
"url": "https://github.com/insyri/tpy/issues"
},
"dependencies": {
"peerDependencies": {
"@types/node": "18.11.3",
"discord-api-types": "0.37.14"
"discord-api-types": "0.37.14",
"node-fetch": "3.2.10"
},
"peerDependenciesMeta": {
"node-fetch": {
"optional": true
}
},
"devDependencies": {
"typescript": "4.8.4"
},
"optionalDependencies": {
"node-fetch": "3.2.10"
}
}
28 changes: 11 additions & 17 deletions src/fetch_polyfill.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
import fetch, {
Blob,
blobFrom,
blobFromSync,
File,
fileFrom,
fileFromSync,
FormData,
Headers,
Request,
Response,
} from 'node-fetch';
// This file is meant to be read by Node.js, Deno stops at line 5.
// If Deno extension enabled, ignore errors.

if (!globalThis.fetch) {
Object.defineProperty(globalThis, 'fetch', fetch);
Object.defineProperty(globalThis, 'Headers', Headers);
Object.defineProperty(globalThis, 'Request', Request);
Object.defineProperty(globalThis, 'Response', Response);
if (
'process' in globalThis && // If Node
Number(globalThis.process.version.substring(1, 3)) < 18
) {
Object.defineProperty(
globalThis,
'fetch',
require('node-fetch'),
);
}
2 changes: 1 addition & 1 deletion src/tpy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import TpyWs from './ws.ts';
import TpyKV from './kv.ts';
import Context from './context.ts';

if (!Deno) await import('./fetch_polyfill.ts');
import './fetch_polyfill.ts';

/**
* The central entity for interacting with the Pylon API; the entrypoint.
Expand Down

0 comments on commit bf87041

Please sign in to comment.