Feat/parse invitation
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
import type { XOInvitation } from '@xo-cash/types';
|
||||
import { fromExtendedJson, toExtendedJson } from '../extended-json.ts';
|
||||
import { InvitationJsonMalformedError, InvitationSerializationFailedError } from './errors.ts';
|
||||
import { parseInvitation } from './parser.ts';
|
||||
|
||||
/**
|
||||
* Serializes an invitation for sharing. Encodes bigint and Uint8Array fields using Extended JSON.
|
||||
*
|
||||
* @param invitation Shared invitation to export.
|
||||
* @returns JSON string that {@link deserializeInvitation} can restore.
|
||||
* @throws {InvitationSerializationFailedError} When JSON serialization fails.
|
||||
*/
|
||||
export const serializeInvitation = (invitation: XOInvitation): string => {
|
||||
try {
|
||||
return toExtendedJson(invitation);
|
||||
} catch (serializationError) {
|
||||
const reason = serializationError instanceof Error ? serializationError.message : 'unknown error while serializing invitation';
|
||||
|
||||
throw new InvitationSerializationFailedError(reason);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Deserializes a shared invitation JSON string into an invitation.
|
||||
*
|
||||
* Every field is checked against its declared type, so the returned invitation can be trusted to match
|
||||
* {@link XOInvitation}.
|
||||
*
|
||||
* @param serializedInvitation JSON produced by {@link serializeInvitation}.
|
||||
* @returns Parsed invitation whose fields match their declared types.
|
||||
* @throws {InvitationJsonMalformedError} When the string is not valid JSON.
|
||||
* @throws {InvitationInvalidError} When the parsed value does not match the XOInvitation type.
|
||||
*/
|
||||
export const deserializeInvitation = (serializedInvitation: string): XOInvitation => {
|
||||
let parsedValue: unknown;
|
||||
|
||||
try {
|
||||
parsedValue = fromExtendedJson(serializedInvitation);
|
||||
} catch (parsingError) {
|
||||
const reason = parsingError instanceof Error ? parsingError.message : 'unknown error while deserializing invitation';
|
||||
|
||||
throw new InvitationJsonMalformedError(reason);
|
||||
}
|
||||
|
||||
return parseInvitation(parsedValue);
|
||||
};
|
||||
Reference in New Issue
Block a user