Closed sicciaman closed 10 months ago
You can provide a custom fetch
implementation for any request method, not just getOne
/getLits
. For more details, please refer to https://github.com/pocketbase/js-sdk?tab=readme-ov-file#services (the optional SendOptions
argument is usually the last one).
If you want to specify a custom fetch
implementation globally for the client you can use the beforeSend
hook and assign a new function to options.fetch
.
Thank you so much! I really appreciate your work, it's awesome!
I'll attach here my custom implementation that uses Angular HttpClient so requests could be catched by any Interceptor in the app.
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import PocketBase, { BeforeSendResult, SendOptions } from 'pocketbase';
import { lastValueFrom, map } from 'rxjs';
import { environment } from 'src/environments/environment';
@Injectable({ providedIn: 'root' })
export class PocketbaseClient {
private readonly httpClient = inject(HttpClient);
private serverUrl: string;
client: PocketBase;
constructor() {
const { serverUrl } = environment.pocketBaseConfig;
this.serverUrl = `${serverUrl}`;
this.client = new PocketBase(this.serverUrl);
this.client.autoCancellation(false);
this.client.beforeSend = this.fetchToHttpClient; (url: string, options: SendOptions) => this.fetchToHttpClient(url, options);
}
private fetchToHttpClient = (url: string, options: SendOptions): BeforeSendResult => {
options.fetch = (url: RequestInfo | URL, config: RequestInit | undefined) => {
const method = config?.method || 'GET';
return lastValueFrom(this.httpClient.request(method, url.toString(),
{ ...options, observe: 'response', responseType: 'arraybuffer' })
.pipe(
map(({ body, headers, status, statusText }: HttpResponse<ArrayBuffer>) => {
const responseHeaders = this.convertHttpHeadersToHeaders(headers);
return new Response(body, { headers: responseHeaders, status, statusText });
})
));
};
return { url, options };
}
private convertHttpHeadersToHeaders(httpHeaders: HttpHeaders): Headers {
const headerMap: Record<string, string> = {};
httpHeaders.keys().forEach(key => {
headerMap[key] = httpHeaders.get(key)!;
});
return new Headers(headerMap);
}
}
Hello! I discovered the possibility of have a custom fetch function implementation, but this is only possible on GetList/GetOne etc. methods. I was trying to apply a more generical approach so I was creating my own instance of Client overriding send method.
But the problem is that some functions used internally are private inside Client class so I can't use it. Do you have any idea on how I could resolve this? Is there a better solution?
Thanks