session and cookie examples

This commit is contained in:
King Wang
2021-06-11 17:46:26 +08:00
parent 69dd082dc8
commit 5af32e67ba
33 changed files with 975 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
import { HttpClient } from "tsrpc-browser";
const CookieStorageKey = '__MY_COOKIE__';
const SessionStorageKey = '__MY_SESSION__';
export function enableSessionAndCookie(client: HttpClient<any>) {
// Send
client.flows.preCallApiFlow.push(v => {
// Auto get __cookie from localStorage
let cookieStr = localStorage.getItem(CookieStorageKey);
v.req.__cookie = cookieStr ? JSON.parse(cookieStr) : undefined;
// Auto get __session from sessionStorage
let sessionStr = sessionStorage.getItem(SessionStorageKey);
v.req.__session = sessionStr ? JSON.parse(sessionStr) : undefined;
return v;
})
// Return
client.flows.preApiReturnFlow.push(v => {
if (v.return.isSucc) {
// Auto set __cookie to localStorage
if (v.return.res.__cookie) {
localStorage.setItem(CookieStorageKey, JSON.stringify(v.return.res.__cookie))
}
// Auto set __session to sessionStorage
if (v.return.res.__session) {
sessionStorage.setItem(SessionStorageKey, JSON.stringify(v.return.res.__session))
}
}
return v;
})
}

View File

@@ -0,0 +1,10 @@
import { HttpClient } from "tsrpc-browser";
export function showReqAndRes(client: HttpClient<any>) {
// Send
client.flows.postApiReturnFlow.push(v => {
(document.querySelector('.apiReq') as HTMLElement).innerText = 'callApi: ' + v.apiName + '\n\n' + JSON.stringify(v.req, null, 2);
(document.querySelector('.apiReturn') as HTMLElement).innerText = JSON.stringify(v.return, null, 2);
return v;
});
}