This repository was archived by the owner on Aug 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreads.ts
86 lines (74 loc) · 2.52 KB
/
threads.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
77
78
79
80
81
82
83
84
85
86
; (global as any).WebSocket = require('isomorphic-ws')
import { KeyInfo, ThreadID, Client } from '@textile/hub'
import { Database, Collection, JSONSchema } from "@textile/threads-database"
import { Libp2pCryptoIdentity } from '@textile/threads-core'
import { config } from 'dotenv'
// Load your .env into process.env
config()
interface Message {
_id: string
author: string
text: string
}
const messageSchema: JSONSchema = {
$schema: 'http://json-schema.org/draft-07/schema#',
definitions: {
ChatBasic: {
title: 'ChatBasic',
type: 'object',
properties: {
_id: {
type: 'string',
},
text: {
type: 'string',
},
author: {
type: 'string',
},
},
required: ['text', 'author', '_id'],
},
},
}
const addListener = async (db: Database, name: string) => {
const filter = `${name}.*.0` // filter to our chat room collection
db.emitter.on(filter, (values: any, type: any) => {
//console.log(values)
const message: Message = values.event.patch;
console.log(message)
})
}
const send = async (collection: Collection<Message>, text: string, author: string) => {
const message: Message = {
_id: '',
author: author,
text: text,
}
await collection.insert(message)
}
const example = async () => {
// DEV: KEY and SECRET should be part of production env
const keyInfo: KeyInfo = {
// Using insecure keys
key: process.env.USER_API_KEY,
secret: '',
// @ts-ignore
type: 1,
}
// DEV: ThreadID needs to be persisted and be part of production env
const threadID = ThreadID.fromString('bafk6ijfdz5eibe47pnqmsl5q55hkzmtvsi4d5q5xxnlb7uqcwdy6n3i')
const db = await Database.withKeyInfo(keyInfo, `build/${threadID.toString()}`)
// DEV: Identity needs to be generated by a PKI provider like MetaMask (deterministic)
const identity = await Libp2pCryptoIdentity.fromRandom()
const thread = await db.start(identity, { threadID: db.threadID })
// const db = await new Client();
// DEV: It's all regular MongoDB from this point onwards
const roomName = 'room101';
await addListener(db, roomName)
const chat = await db.collections.get(roomName) || await db.newCollection(roomName, messageSchema);
setTimeout(() => {
send(chat, 'hello', 'Ahmed')
}, 2000)
}
example()