-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathindex.js
84 lines (73 loc) · 2.23 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
/**
* Created by lvbingru on 1/5/16.
*/
import {NativeModules, NativeAppEventEmitter} from 'react-native';
const {WeiboAPI} = NativeModules;
function wrapApi(nativeFunc) {
if (!nativeFunc) {
return undefined;
}
return (...args) => {
return new Promise((resolve, reject) => {
nativeFunc.apply(null, [
...args,
(error, result) => {
if (!error) {
return resolve(result);
}
if (typeof error === 'string') {
return reject(new Error(error));
}
reject(error);
},
]);
});
};
}
// Save callback and wait for future event.
let savedCallback = undefined;
function waitForResponse(type) {
return new Promise((resolve, reject) => {
if (savedCallback) {
savedCallback('User canceled.');
}
savedCallback = result => {
if (result.type !== type) {
return;
}
savedCallback = undefined;
if (result.errCode !== 0) {
const err = new Error(result.errMsg);
err.errCode = result.errCode;
reject(err);
} else {
resolve(result);
}
};
});
}
NativeAppEventEmitter.addListener('Weibo_Resp', resp => {
const callback = savedCallback;
savedCallback = undefined;
callback && callback(resp);
});
const defaultScope = "all"
const defaultRedirectURI = "https://api.weibo.com/oauth2/default.html"
function checkData(data) {
if(!data.redirectURI) {
data.redirectURI = defaultRedirectURI
}
if(!data.scope) {
data.scope = defaultScope
}
}
const nativeSendAuthRequest = wrapApi(WeiboAPI.login);
const nativeSendMessageRequest = wrapApi(WeiboAPI.shareToWeibo);
export function login(config={}) {
checkData(config)
return Promise.all([waitForResponse('WBAuthorizeResponse'), nativeSendAuthRequest(config)]).then(v=>v[0]);
}
export function share(data) {
checkData(data)
return Promise.all([waitForResponse('WBSendMessageToWeiboResponse'), nativeSendMessageRequest(data)]).then(v=>v[0]);
}