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

Replace http-client got with ky, improving browser compatibility #695

Open
wants to merge 1 commit into
base: master
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
7 changes: 3 additions & 4 deletions lib/coverartarchive-api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable-next-line */
import got from 'got';
import got from 'ky';

export type CovertType = 'Front' | 'Back' | 'Booklet' | 'Medium' | 'Obi' | 'Spine' | 'Track' | 'Tray' | 'Sticker' |
'Poster' | 'Liner' | 'Watermark' | 'Raw/Unedited' | 'Matrix/Runout' | 'Top' | 'Bottom' | 'Other';
Expand Down Expand Up @@ -35,10 +35,9 @@ export class CoverArtArchiveApi {
const response = await got.get(`https://${this.host}${path}`, {
headers: {
Accept: "application/json"
},
responseType: 'json'
}
});
return response.body;
return response.json();
}

/**
Expand Down
59 changes: 27 additions & 32 deletions lib/musicbrainz-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,11 @@ import { DigestAuth } from './digest-auth.js';
import { RateLimitThreshold } from 'rate-limit-threshold';
import * as mb from './musicbrainz.types.js';

import got, {type Options, type ToughCookieJar} from 'got';

import ky, {Options} from 'ky';
import {type Cookie, CookieJar} from 'tough-cookie';

export * from './musicbrainz.types.js';

import { promisify } from 'node:util';

/*
* https://musicbrainz.org/doc/Development/XML_Web_Service/Version_2#Subqueries
*/
Expand Down Expand Up @@ -202,18 +199,16 @@ export class MusicBrainzApi {
Object.assign(this.config, _config);

const cookieJar: CookieJar = new CookieJar();
this.getCookies = promisify(cookieJar.getCookies.bind(cookieJar));
this.getCookies = cookieJar.getCookies;

// @ts-ignore
this.options = {
prefixUrl: this.config.baseUrl as string,
timeout: {
read: 20 * 1000
},
timeout: 20 * 1000,
headers: {
'User-Agent': `${this.config.appName}/${this.config.appVersion} ( ${this.config.appContactInfo} )`
},
cookieJar: cookieJar as ToughCookieJar
}
// cookieJar: cookieJar as ToughCookieJar
};

this.rateLimiter = new RateLimitThreshold(15, 18);
Expand All @@ -224,15 +219,14 @@ export class MusicBrainzApi {
query.fmt = 'json';

await this.applyRateLimiter();
const response: any = await got.get(`ws/2${relUrl}`, {
const response: any = await ky.get(`ws/2${relUrl}`, {
...this.options,
searchParams: query,
responseType: 'json',
retry: {
limit: 10
}
});
return response.body;
return response.json();
}

/**
Expand Down Expand Up @@ -334,7 +328,7 @@ export class MusicBrainzApi {

do {
await this.applyRateLimiter();
const response: any = await got.post(path, {
const response: any = await ky.post(path, {
...this.options,
searchParams: {client: clientId},
headers: {
Expand Down Expand Up @@ -380,15 +374,18 @@ export class MusicBrainzApi {
remember_me: 1
};

const response = await got.post('login', {
const response = await ky.post('login', {
...this.options,
followRedirect: false,
searchParams: {
returnto: redirectUri
},
form: formData
json: formData
});
const success = response.statusCode === HttpStatus.MOVED_TEMPORARILY && response.headers.location === redirectUri;

// ToDo: followRedirect: false,
//

const success = response.status === HttpStatus.MOVED_TEMPORARILY && response.headers.get('location') === redirectUri;
if (success) {
this.session.loggedIn = true;
}
Expand All @@ -401,14 +398,14 @@ export class MusicBrainzApi {
public async logout(): Promise<boolean> {
const redirectUri = '/success';

const response = await got.get('logout', {
const response = await ky.get('logout', {
...this.options,
followRedirect: false,
searchParams: {
returnto: redirectUri
}
});
const success = response.statusCode === HttpStatus.MOVED_TEMPORARILY && response.headers.location === redirectUri;
// ToDo: followRedirect: false,
const success = response.status === HttpStatus.MOVED_TEMPORARILY && response.headers.get('location') === redirectUri;
if (success && this.session) {
this.session.loggedIn = true;
}
Expand All @@ -433,16 +430,16 @@ export class MusicBrainzApi {
formData.password = this.config.botAccount?.password;
formData.remember_me = 1;

const response = await got.post(`${entity}/${mbid}/edit`, {
const response = await ky.post(`${entity}/${mbid}/edit`, {
...this.options,
form: formData,
followRedirect: false
json: formData,redirect: 'error',
// followRedirect: false
});
if (response.statusCode === HttpStatus.OK)
if (response.status === HttpStatus.OK)
throw new Error("Failed to submit form data");
if (response.statusCode === HttpStatus.MOVED_TEMPORARILY)
if (response.status === HttpStatus.MOVED_TEMPORARILY)
return;
throw new Error(`Unexpected status code: ${response.statusCode}`);
throw new Error(`Unexpected status code: ${response.status}`);
}

/**
Expand Down Expand Up @@ -520,14 +517,12 @@ export class MusicBrainzApi {

private async getSession(): Promise<ISessionInformation> {

const response = await got.get('login', {
const response = await ky.get('login', {
...this.options,
followRedirect: false, // Disable redirects
responseType: 'text'
});

// Too followRedirect: false, // Disable redirects
return {
csrf: MusicBrainzApi.fetchCsrf(response.body)
csrf: MusicBrainzApi.fetchCsrf(await response.text())
};
}

Expand Down
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@
"@types/uuid": "^10.0.0",
"caseless": "^0.12.0",
"debug": "^4.3.4",
"got": "^14.2.1",
"http-status-codes": "^2.1.4",
"json-stringify-safe": "^5.0.1",
"jsontoxml": "^1.0.1",
"ky": "^1.7.0",
"rate-limit-threshold": "^0.1.5",
"source-map-support": "^0.5.16",
"tough-cookie": "^4.1.3",
Expand Down Expand Up @@ -104,6 +104,5 @@
"text"
],
"report-dir": "coverage"
},
"packageManager": "[email protected]"
}
}
10 changes: 5 additions & 5 deletions test/test-musicbrainz-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import type * as mb from '../lib/musicbrainz.types.js';
import { readFile } from 'node:fs/promises';
import sinon from 'sinon';
import { RateLimitThreshold } from 'rate-limit-threshold';
import got from 'got';
import got from 'ky';

const appUrl = 'https://github.com/Borewit/musicbrainz-api';

Expand Down Expand Up @@ -926,7 +926,7 @@ describe('MusicBrainz-api', function () {

beforeEach(() => {
// Stub to avoid unecessary HTTP requests in the context of these tests
sinon.stub(got, "get").resolves({});
sinon.stub(got, "get").resolves();
});

it("rate limits by default", async () => {
Expand Down Expand Up @@ -959,7 +959,7 @@ describe('MusicBrainz-api', function () {

beforeEach(() => {
// Stub to avoid unecessary HTTP requests in the context of these tests
sinon.stub(got, "post").resolves({});
sinon.stub(got, "post").resolves();
});

it("rate limits by default", async () => {
Expand All @@ -985,8 +985,8 @@ describe('MusicBrainz-api', function () {
describe.skip('editEntity', () => {

beforeEach(() => {
// Stub to avoid unecessary HTTP requests in the context of these tests
sinon.stub(got, "post").resolves({});
// Stub to avoid unnecessary HTTP requests in the context of these tests
sinon.stub(got, "post").resolves();
});

it("rate limits by default", async () => {
Expand Down
Loading
Loading