Move RelayError into its own file, add helper methods

This commit is contained in:
Alex Gleason
2024-05-14 14:38:05 -05:00
parent 4029971407
commit ecfea827e1
4 changed files with 31 additions and 21 deletions

24
src/RelayError.ts Normal file
View File

@@ -0,0 +1,24 @@
import { NostrRelayOK } from '@nostrify/nostrify';
export type RelayErrorPrefix = 'duplicate' | 'pow' | 'blocked' | 'rate-limited' | 'invalid' | 'error';
/** NIP-01 command line result. */
export class RelayError extends Error {
constructor(prefix: RelayErrorPrefix, message: string) {
super(`${prefix}: ${message}`);
}
/** Construct a RelayError from the reason message. */
static fromReason(reason: string): RelayError {
const [prefix, ...rest] = reason.split(': ');
return new RelayError(prefix as RelayErrorPrefix, rest.join(': '));
}
/** Throw a new RelayError if the OK message is false. */
static assert(msg: NostrRelayOK): void {
const [_, _eventId, ok, reason] = msg;
if (!ok) {
throw RelayError.fromReason(reason);
}
}
}