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

Use builtin fetch for Node if exists #2

Merged
merged 1 commit into from
Apr 22, 2024
Merged
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
55 changes: 0 additions & 55 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 5 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,19 @@
"test": "node --experimental-vm-modules node_modules/.bin/jest"
},
"jest": {
"testPathIgnorePatterns": ["examples"]
"testPathIgnorePatterns": [
"examples"
]
},
"repository": {
"type": "git",
"url": "https://github.com/platformatic/mistral-client"
},
"types": "src/client.d.ts",
"dependencies": {
"node-fetch": "^2.6.7"
},
"devDependencies": {
"eslint": "^8.55.0",
"eslint-config-google": "^0.14.0",
"prettier": "2.8.8",
"jest": "^29.7.0"
"jest": "^29.7.0",
"prettier": "2.8.8"
}
}
42 changes: 1 addition & 41 deletions src/client.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,7 @@
let isNode = false;

const VERSION = '0.0.3';
const RETRY_STATUS_CODES = [429, 500, 502, 503, 504];
const ENDPOINT = 'https://api.mistral.ai';

/**
* Initialize fetch
* @return {Promise<void>}
*/
async function initializeFetch() {
if (typeof window === 'undefined' ||
typeof globalThis.fetch === 'undefined') {
const nodeFetch = await import('node-fetch');
fetch = nodeFetch.default;
isNode = true;
} else {
fetch = globalThis.fetch;
}
}

initializeFetch();

/**
* MistralAPIError
* @return {MistralAPIError}
Expand Down Expand Up @@ -94,28 +75,7 @@ class MistralClient {

if (response.ok) {
if (request?.stream) {
if (isNode) {
return response.body;
} else {
const reader = response.body.getReader();
// Chrome does not support async iterators yet, so polyfill it
const asyncIterator = async function* () {
try {
while (true) {
// Read from the stream
const {done, value} = await reader.read();
// Exit if we're done
if (done) return;
// Else yield the chunk
yield value;
}
} finally {
reader.releaseLock();
}
};

return asyncIterator();
}
return response.body;
}
return await response.json();
} else if (RETRY_STATUS_CODES.includes(response.status)) {
Expand Down