mirror of
https://gitcode.com/gh_mirrors/re/react-native-pushy.git
synced 2025-10-08 22:45:16 +08:00
support login & logout & me
This commit is contained in:
@@ -3,16 +3,17 @@
|
||||
*/
|
||||
|
||||
const fetch = require('isomorphic-fetch');
|
||||
const host = process.env.PUSHY_REGISTRY || 'http://pushy.reactnative.cn';
|
||||
let host = process.env.PUSHY_REGISTRY || 'http://pushy.reactnative.cn';
|
||||
const fs = require('fs-promise');
|
||||
|
||||
let session = undefined;
|
||||
let fileSession = undefined;
|
||||
let savedSession = undefined;
|
||||
|
||||
exports.loadSession = async function() {
|
||||
if (await fs.exists('.pushy')) {
|
||||
try {
|
||||
session = JSON.parse(await fs.readFile('.pushy', 'utf8'));
|
||||
exports.replaceSession(JSON.parse(await fs.readFile('.pushy', 'utf8')));
|
||||
savedSession = session;
|
||||
} catch (e) {
|
||||
console.error('Failed to parse file `.pushy`. Try to remove it manually.');
|
||||
throw e;
|
||||
@@ -30,26 +31,56 @@ exports.replaceSession = function(newSession) {
|
||||
|
||||
exports.saveSession = async function(){
|
||||
// Only save on change.
|
||||
if (session != fileSession) {
|
||||
if (session !== savedSession) {
|
||||
const current = session;
|
||||
const data = JSON.stringify(current, null, 4);
|
||||
await fs.writeFile('.pushy', data, 'utf8');
|
||||
fileSession = current;
|
||||
savedSession = current;
|
||||
}
|
||||
}
|
||||
|
||||
function queryWithBody(method){
|
||||
return async function(api, body) {
|
||||
const resp = await fetch(host + api, {
|
||||
method: 'post',
|
||||
exports.closeSession = async function(){
|
||||
if (await fs.exists('.pushy')) {
|
||||
await fs.unlink('.pushy');
|
||||
savedSession = undefined;
|
||||
}
|
||||
session = undefined;
|
||||
host = process.env.PUSHY_REGISTRY || 'http://pushy.reactnative.cn';
|
||||
}
|
||||
|
||||
async function query(url, options) {
|
||||
const resp = await fetch(url, options);
|
||||
const json = await resp.json();
|
||||
if (resp.status !== 200) {
|
||||
throw Object.assign(new Error(json.message || json.error), {status: resp.status});
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
function queryWithoutBody(method) {
|
||||
return function(api) {
|
||||
return query(host + api, {
|
||||
method,
|
||||
headers: {
|
||||
'X-AccessToken': session ? session.token : '',
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function queryWithBody(method) {
|
||||
return function(api, body) {
|
||||
return query(host + api, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-AccessToken': session ? session.token : '',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
exports.get = queryWithoutBody('GET');
|
||||
exports.post = queryWithBody('POST');
|
||||
exports.put = queryWithBody('PUT');
|
||||
|
Reference in New Issue
Block a user