generated from TBD54566975/tbd-project-template
/
messages-get.ts
59 lines (49 loc) · 2.08 KB
/
messages-get.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import type { Signer } from '../types/signer.js';
import type { MessagesGetDescriptor, MessagesGetMessage } from '../types/messages-types.js';
import { AbstractMessage } from '../core/abstract-message.js';
import { Cid } from '../utils/cid.js';
import { Message } from '../core/message.js';
import { Time } from '../utils/time.js';
import { DwnError, DwnErrorCode } from '../core/dwn-error.js';
import { DwnInterfaceName, DwnMethodName } from '../enums/dwn-interface-method.js';
export type MessagesGetOptions = {
messageCids: string[];
signer: Signer;
messageTimestamp?: string;
};
export class MessagesGet extends AbstractMessage<MessagesGetMessage> {
public static async parse(message: MessagesGetMessage): Promise<MessagesGet> {
Message.validateJsonSchema(message);
this.validateMessageCids(message.descriptor.messageCids);
await Message.validateSignatureStructure(message.authorization.signature, message.descriptor);
Time.validateTimestamp(message.descriptor.messageTimestamp);
return new MessagesGet(message);
}
public static async create(options: MessagesGetOptions): Promise<MessagesGet> {
const descriptor: MessagesGetDescriptor = {
interface : DwnInterfaceName.Messages,
method : DwnMethodName.Get,
messageCids : options.messageCids,
messageTimestamp : options?.messageTimestamp ?? Time.getCurrentTimestamp(),
};
const authorization = await Message.createAuthorization({ descriptor, signer: options.signer });
const message = { descriptor, authorization };
Message.validateJsonSchema(message);
MessagesGet.validateMessageCids(options.messageCids);
return new MessagesGet(message);
}
/**
* validates the provided cids
* @param messageCids - the cids in question
* @throws {DwnError} if an invalid cid is found.
*/
private static validateMessageCids(messageCids: string[]): void {
for (const cid of messageCids) {
try {
Cid.parseCid(cid);
} catch (_) {
throw new DwnError(DwnErrorCode.MessageGetInvalidCid, `${cid} is not a valid CID`);
}
}
}
}