Files
snort/packages/nostr/src/common.ts
sistemd 05605bdf28 nostr package: vastly simplify the API (#412)
* vastly simplify the api

* add missing await

* add eose to emitter

* add eose to conn

* add eose to the client

* eose test

* improve test suite, add dm tests

* demonstrate that nostr-rs-relay auth options don't work

* readme files

* cleanup

* fetch relay info

* test readyState

* export fetchRelayInfo

* cleanup

* better async/await linting

* use strictEqual in tests

* additional eslint rules

* allow arbitrary extensions

* saner error handling

* update README

* implement nip-02

---------

Co-authored-by: Kieran <kieran@harkin.me>
2023-03-27 10:09:48 +01:00

43 lines
956 B
TypeScript

/**
* A UNIX timestamp.
*/
export type Timestamp = number
/**
* Calculate the unix timestamp (seconds since epoch) of the `Date`. If no date is specified,
* return the current unix timestamp.
*/
export function unixTimestamp(date?: Date): Timestamp {
return Math.floor((date ?? new Date()).getTime() / 1000)
}
/**
* Throw if the parameter is null or undefined. Return the parameter otherwise.
*/
export function defined<T>(v: T | undefined | null): T {
if (v === undefined || v === null) {
throw new NostrError("bug: unexpected undefined")
}
return v
}
/**
* Parse the JSON and throw a @see {@link NostrError} in case of error.
*/
export function parseJson(data: string) {
try {
return JSON.parse(data)
} catch (e) {
throw new NostrError(`invalid json: ${e}: ${data}`)
}
}
/**
* The error thrown by this library.
*/
export class NostrError extends Error {
constructor(message?: string) {
super(message)
}
}