-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
110 lines (92 loc) · 2.42 KB
/
index.js
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import axios from 'axios'
import { sign } from './libs/sign_client'
import Login from './login'
import { DEFAULT_NODE } from './const'
import style from './style'
import { hashString, insertStyle, appendMessageEl, showMessage } from './libs/common'
import { v4 as uuidv4 } from 'uuid'
export default class {
constructor({ node, showLog = false, loginAddress, wallet } = {}) {
this.node = node || DEFAULT_NODE
this.wallet = wallet || 'metamask'
// remove EVM/ prefix if exists
if (loginAddress) {
loginAddress = loginAddress.replace(/^EVM\//i, '')
}
this.login = new Login({ node: this.node, showLog, loginAddress, wallet })
this.localstoragePrefix = `echo_${hashString(this.node)}_`
insertStyle(style(), 'echo-login-style')
this.$message = appendMessageEl()
return this
}
getCommonHeader() {
return {
Authorization: `Bearer ${this.login.getToken()}`
}
}
isAuthorized() {
return this.login.hasLogined
}
getAuthorizedInfo() {
return this.login.getUserInfo()
}
async authorize() {
return await this.login.login()
}
showMessage(type, text) {
return showMessage(this.$message, type, text)
}
async getPosts({ target_uri, type, created_by = null } = {}) {
if (!target_uri) {
throw new Error('TARGET_URI IS REQUIRED')
}
try {
const rs = await axios.get(`${this.node}/api/v1/posts`, {
params: {
target_uri,
type,
created_by
}
})
return rs.data
} catch (e) {
if (e.response && e.response.data && e.response.data.msg) {
throw new Error(e.response.data.msg)
} else {
throw e
}
}
}
async post(data) {
if (!this.login.hasLogined) {
try {
const rs = await this.login.login()
if (!rs) {
return
}
} catch (e) {
throw e
}
}
const body = {
protocol_version: '0.1',
...data,
id: uuidv4()
}
const signed = sign(body, this.localstoragePrefix)
body.public_key = signed.publicKey
body.signature = signed.signature
try {
const rs = await axios.post(`${this.node}/api/v1/posts`, body, {
headers: this.getCommonHeader()
})
return rs.data
} catch (e) {
if (e.response && e.response.data && e.response.data.msg) {
throw new Error(e.response.data.msg)
} else {
throw e
}
}
}
}