forked from coasys/neighbourhood-language
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adapter.ts
76 lines (64 loc) · 2.21 KB
/
adapter.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import type { Address, Expression, ExpressionAdapter, PublicSharing, LanguageContext, AgentService, HolochainLanguageDelegate } from "@perspect3vism/ad4m";
import type { IPFS } from "ipfs-core-types";
import axios from "axios";
import https from "https";
import { BUCKET_NAME, s3, UPLOAD_ENDPOINT } from "./config";
import type { Readable } from "stream";
import { GetObjectCommand } from "@aws-sdk/client-s3";
class SharedPerspectivePutAdapter implements PublicSharing {
#agent: AgentService;
#IPFS: IPFS;
constructor(context: LanguageContext) {
this.#agent = context.agent;
this.#IPFS = context.IPFS;
}
async createPublic(neighbourhood: object): Promise<Address> {
const agent = this.#agent;
const expression = agent.createSignedExpression(neighbourhood);
const content = JSON.stringify(expression);
const result = await this.#IPFS.add(
{ content },
{ onlyHash: true },
);
const hash = result.cid.toString();
const httpsAgent = new https.Agent({
rejectUnauthorized: false
});
const postData = {
hash,
content,
};
const postResult = await axios.post(UPLOAD_ENDPOINT, postData, { httpsAgent });
if (postResult.status != 200) {
console.error("Create neighbourhood error: ", postResult);
}
// @ts-ignore
return hash as Address;
}
}
async function streamToString(stream: Readable): Promise<string> {
return await new Promise((resolve, reject) => {
const chunks: Uint8Array[] = [];
stream.on('data', (chunk) => chunks.push(chunk));
stream.on('error', reject);
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
})
}
export default class Adapter implements ExpressionAdapter {
#IPFS: IPFS;
putAdapter: PublicSharing;
constructor(context: LanguageContext) {
this.#IPFS = context.IPFS;
this.putAdapter = new SharedPerspectivePutAdapter(context);
}
async get(address: Address): Promise<Expression> {
const cid = address.toString();
const params = {
Bucket: BUCKET_NAME,
Key: cid,
};
const response = await s3.send(new GetObjectCommand(params));
const contents = await streamToString(response.Body as Readable);
return JSON.parse(contents);
}
}