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

feat: export ws events #253

Closed
wants to merge 1 commit into from
Closed

Conversation

FoxxMD
Copy link

@FoxxMD FoxxMD commented Jun 6, 2024

Description

Exports event types from events.js so that they can properly used in Typescript code. Without this export in package.json typescript complains there is no module when trying to do

import { CloseEvent, ErrorEvent, RetryEvent } from "iso-websocket/dist/src/events.js";

Type of change

  • New feature (non-breaking change that adds functionality)

@FoxxMD FoxxMD requested a review from hugomrdias as a code owner June 6, 2024 16:42
@hugomrdias
Copy link
Owner

your PR will not solve the issue, whats your use case ?

@FoxxMD
Copy link
Author

FoxxMD commented Jun 12, 2024

I want to be able to type guard against events so I can use them outside of .onclose or .addEventListener, ('error', ...), etc...

import { WS, CloseEvent, ErrorEvent, RetryEvent  } from 'iso-websocket'

const isCloseEvent = (e: Event): e is CloseEvent => {
    return e.type === 'close';
}
const isErrorEvent = (e: Event): e is ErrorEvent => {
    return e.type === 'error';
}
const isRetryEvent = (e: Event): e is RetryEvent => {
    return e.type === 'retry';
}


class MyClass {

    // rest of code omitted...

    doAuthentication = async () => {
        try {
            const authRace = Promise.race([
                pEvent(this.client, 'message'),
                pEvent(this.client, 'close'),
                sleep(2000),
            ]);
            this.client.send(JSON.stringify(this.getAuthPayload()));
            const authE = await authRace;
            if(authE === undefined) {
                throw new Error('Musikcube did not respond to auth message after 2000 ms');
            } else if(isCloseEvent(authE)) {
                throw new Error(`Password is not correct: ${authE.code} => ${authE.reason}`);
            } else if(isErrorEvent(authE)) {
                throw new Error(`Unexpected error occurred while authenticating: ${authE.message}`, {cause: authE.error});
            }

            return true;
        } catch (e) {
            throw e;
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants