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

Make SDK realtime composable compatible with React Native #22105

Merged
merged 8 commits into from Apr 25, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/lucky-rivers-taste.md
@@ -0,0 +1,5 @@
---

Check warning on line 1 in .changeset/lucky-rivers-taste.md

View workflow job for this annotation

GitHub Actions / Lint

File ignored by default.
'@directus/sdk': major
---

Made the SDK realtime composable compatible with React Native, the WebSocket client will now be initialized with the URL as `string` instead of `URL`
10 changes: 6 additions & 4 deletions sdk/src/realtime/composable.ts
Expand Up @@ -58,17 +58,19 @@ export function realtime(config: WebSocketConfig = {}) {
const debug = (level: keyof ConsoleInterface, ...data: any[]) =>
config.debug && client.globals.logger[level]('[Directus SDK]', ...data);

const withStrictAuth = async (url: URL, currentClient: AuthWSClient<Schema>) => {
const withStrictAuth = async (url: URL | string, currentClient: AuthWSClient<Schema>) => {
const newUrl = new client.globals.URL(url);

if (config.authMode === 'strict' && hasAuth(currentClient)) {
const token = await currentClient.getToken();
if (token) url.searchParams.set('access_token', token);
if (token) newUrl.searchParams.set('access_token', token);
}

return url;
return newUrl.toString();
};

const getSocketUrl = async (currentClient: AuthWSClient<Schema>) => {
if ('url' in config) return await withStrictAuth(new client.globals.URL(config.url), currentClient);
if ('url' in config) return await withStrictAuth(config.url, currentClient);

// if the main URL is a websocket URL use it directly!
if (['ws:', 'wss:'].includes(client.url.protocol)) {
Expand Down
3 changes: 2 additions & 1 deletion sdk/src/types/globals.ts
Expand Up @@ -3,8 +3,9 @@ export type FetchInterface = (input: string | any, init?: RequestInit | any) =>

export type UrlInterface = typeof URL;

/** While the standard says 'string | URL' for the 'url' parameter, some implementations (e.g. React Native) only accept 'string' */
export type WebSocketConstructor = {
new (url: URL, protocols?: string | string[]): WebSocketInterface;
new (url: string, protocols?: string | string[]): WebSocketInterface;
};

export type WebSocketInterface = {
Expand Down