client.ts

This commit is contained in:
King Wang 2021-06-14 21:17:30 +08:00
parent 7717225411
commit d333f6c97d
2 changed files with 37 additions and 34 deletions

View File

@ -0,0 +1,34 @@
import { HttpClient } from "tsrpc-browser";
import { setStatus } from "./index";
import { BaseResponse } from "./shared/protocols/base";
import { serviceProto } from "./shared/protocols/serviceProto";
// Create Client
export const client = new HttpClient(serviceProto, {
server: 'http://127.0.0.1:3000',
logger: console
});
// When server return a SSOToken, store it to localStorage
client.flows.postApiReturnFlow.push(v => {
if (v.return.isSucc) {
let res = v.return.res as BaseResponse;
if (res.__ssoToken !== undefined) {
localStorage.setItem('SSO_TOKEN', res.__ssoToken);
}
}
else if (v.return.err.code === 'NEED_LOGIN') {
localStorage.removeItem('SSO_TOKEN');
setStatus(false);
}
return v;
});
// Append "__ssoToken" to request automatically
client.flows.preCallApiFlow.push(v => {
let ssoToken = localStorage.getItem('SSO_TOKEN');
if (ssoToken) {
v.req.__ssoToken = ssoToken;
}
return v;
})

View File

@ -1,38 +1,7 @@
import { HttpClient } from 'tsrpc-browser'; import { client } from "./client";
import { BaseResponse } from './shared/protocols/base';
import { serviceProto } from './shared/protocols/serviceProto';
const $ = document.querySelector.bind(document) as (v: string) => HTMLElement; const $ = document.querySelector.bind(document) as (v: string) => HTMLElement;
// Create Client
let client = new HttpClient(serviceProto, {
server: 'http://127.0.0.1:3000',
logger: console
});
// When server return a SSOToken, store it to localStorage
client.flows.postApiReturnFlow.push(v => {
if (v.return.isSucc) {
let res = v.return.res as BaseResponse;
if (res.__ssoToken !== undefined) {
localStorage.setItem('SSO_TOKEN', res.__ssoToken);
}
}
else if (v.return.err.code === 'NEED_LOGIN') {
localStorage.removeItem('SSO_TOKEN');
setStatus(false);
}
return v;
});
// Append "__ssoToken" to request automatically
client.flows.preCallApiFlow.push(v => {
let ssoToken = localStorage.getItem('SSO_TOKEN');
if (ssoToken) {
v.req.__ssoToken = ssoToken;
}
return v;
})
// Login & Logout // Login & Logout
$('.login-normal button').onclick = async () => { $('.login-normal button').onclick = async () => {
let ret = await client.callApi('user/Login', { let ret = await client.callApi('user/Login', {
@ -96,7 +65,7 @@ $('.action .admin button').onclick = async () => {
$('.action .admin .return').style.display = 'block'; $('.action .admin .return').style.display = 'block';
} }
function setStatus(logined: boolean) { export function setStatus(logined: boolean) {
if (logined) { if (logined) {
$('.status').className = 'status logined'; $('.status').className = 'status logined';
$('.status').innerText = `Logined as ${localStorage.getItem('LoginedRole')} Role`; $('.status').innerText = `Logined as ${localStorage.getItem('LoginedRole')} Role`;