sessioin-and-cookie example

This commit is contained in:
King Wang 2021-06-14 17:45:11 +08:00
parent 5af32e67ba
commit 54c2f31f83
28 changed files with 297 additions and 233 deletions

View File

@ -12,12 +12,14 @@
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^15.12.2", "@types/node": "^15.12.2",
"@types/uuid": "^8.3.0",
"onchange": "^7.1.0", "onchange": "^7.1.0",
"ts-node": "^9.1.1", "ts-node": "^9.1.1",
"tsrpc-cli": "^2.0.1-dev.11", "tsrpc-cli": "^2.0.1-dev.11",
"typescript": "^4.3.2" "typescript": "^4.3.2"
}, },
"dependencies": { "dependencies": {
"tsrpc": "^3.0.0-dev.19" "tsrpc": "^3.0.0-dev.19",
"uuid": "^8.3.2"
} }
} }

View File

@ -3,7 +3,6 @@ import { ReqClear, ResClear } from "../shared/protocols/PtlClear";
export async function ApiClear(call: ApiCall<ReqClear, ResClear>) { export async function ApiClear(call: ApiCall<ReqClear, ResClear>) {
call.succ({ call.succ({
__cookie: {}, __cookie: {}
__session: {}
}) })
} }

View File

@ -1,13 +0,0 @@
import { ApiCall } from "tsrpc";
import { ReqGetCookie, ResGetCookie } from "../shared/protocols/PtlGetCookie";
let times = 0;
export async function ApiGetCookie(call: ApiCall<ReqGetCookie, ResGetCookie>) {
call.succ({
__cookie: {
...call.req.__cookie,
testCookie: 'Cookie ' + (++times),
}
})
}

View File

@ -1,13 +0,0 @@
import { ApiCall } from "tsrpc";
import { ReqGetSession, ResGetSession } from "../shared/protocols/PtlGetSession";
let times = 0;
export async function ApiGetSession(call: ApiCall<ReqGetSession, ResGetSession>) {
call.succ({
__session: {
...call.req.__session,
testSession: 'Session ' + (++times)
}
})
}

View File

@ -0,0 +1,14 @@
import { ApiCall } from "tsrpc";
import { ReqSetCookie, ResSetCookie } from "../shared/protocols/PtlSetCookie";
let times = 0;
export async function ApiSetCookie(call: ApiCall<ReqSetCookie, ResSetCookie>) {
++times;
call.succ({
__cookie: {
...call.req.__cookie,
testCookie: 'Cookie ' + times,
}
})
}

View File

@ -0,0 +1,10 @@
import { ApiCall } from "tsrpc";
import { ReqSetSession, ResSetSession } from "../shared/protocols/PtlSetSession";
let times = 0;
export async function ApiSetSession(call: ApiCall<ReqSetSession, ResSetSession>) {
++times;
await call.setSession('testSession', 'Session ' + times);
call.succ({})
}

View File

@ -2,5 +2,8 @@ import { ApiCall } from "tsrpc";
import { ReqTest, ResTest } from "../shared/protocols/PtlTest"; import { ReqTest, ResTest } from "../shared/protocols/PtlTest";
export async function ApiTest(call: ApiCall<ReqTest, ResTest>) { export async function ApiTest(call: ApiCall<ReqTest, ResTest>) {
call.succ({}); let testSession = await call.getSession('testSession');
call.succ({
testSession: testSession
});
} }

View File

@ -1,6 +1,7 @@
import * as path from "path"; import * as path from "path";
import { HttpServer } from "tsrpc"; import { HttpServer } from "tsrpc";
import { BaseRequest, BaseResponse } from "./shared/protocols/base"; import { enableCookie } from "./models/enableCookie";
import { ServerSession } from "./models/ServerSession";
import { serviceProto } from "./shared/protocols/serviceProto"; import { serviceProto } from "./shared/protocols/serviceProto";
// Create the Server // Create the Server
@ -9,16 +10,11 @@ const server = new HttpServer(serviceProto, {
cors: '*' cors: '*'
}); });
// Return session and cookie as they are, except reset by res // Enable Cookie
server.flows.preApiReturnFlow.push(v => { enableCookie(server);
if (v.return.isSucc) {
let req = v.call.req as BaseRequest; // Enable Session
let res = v.return.res as BaseResponse; new ServerSession().enable(server);
res.__session = res.__session ?? req.__session;
res.__cookie = res.__cookie ?? req.__cookie;
}
return v;
});
// Entry function // Entry function
async function main() { async function main() {

View File

@ -0,0 +1,68 @@
import { HttpServer } from "tsrpc";
import * as uuid from "uuid";
import { BaseRequest } from "../shared/protocols/base";
// This example store session data to memory for convinience.
// You can store it into database or redis as you need.
export class ServerSession {
async enable(server: HttpServer) {
server.flows.preApiCallFlow.push(async v => {
// Init Session
let req = v.req as BaseRequest;
let { sessionId } = await this.initSession(req.__cookie?.sessionId)
req.__cookie = {
...req.__cookie,
sessionId: sessionId
}
// ApiCall: Get & Set Session
v.getSession = this.getSession.bind(this, sessionId);
v.setSession = this.setSession.bind(this, sessionId);
return v;
});
}
// Test session storage
private _sessionData: {
[sessionId: string]: SessionData;
} = {};
// Storage in server memory for test
// You can modify it to storage into redis / database...
async initSession(sessionId?: string) {
// Existed sessionId
if (sessionId) {
if (this._sessionData[sessionId]) {
return {
sessionId: sessionId
}
}
}
sessionId = uuid.v4();
this._sessionData[sessionId] = {};
return {
sessionId: sessionId
};
}
async getSession<T extends keyof SessionData>(sessioinId: string, key: T): Promise<SessionData[T]> {
return this._sessionData[sessioinId][key];
}
async setSession<T extends keyof SessionData>(sessioinId: string, key: T, value: SessionData[T]): Promise<void> {
this._sessionData[sessioinId][key] = value;
}
}
declare module 'tsrpc' {
export interface ApiCall {
getSession: <T extends keyof SessionData>(key: T) => Promise<SessionData[T]>,
setSession: <T extends keyof SessionData>(key: T, value: SessionData[T]) => Promise<void>
}
}
// Your custom session type definition
export interface SessionData {
testSession?: string
}

View File

@ -0,0 +1,14 @@
import { HttpServer } from "tsrpc";
import { BaseRequest, BaseResponse, Cookie } from "../shared/protocols/base";
export async function enableCookie(server: HttpServer) {
server.flows.preApiReturnFlow.push(v => {
if (v.return.isSucc) {
let req = v.call.req as BaseRequest;
let res = v.return.res as BaseResponse;
// Reset by API handler, or return as they are in the request
res.__cookie = res.__cookie ?? req.__cookie;
}
return v;
});
}

View File

@ -1,9 +0,0 @@
import { BaseRequest, BaseResponse } from './base'
export interface ReqGetCookie extends BaseRequest {
}
export interface ResGetCookie extends BaseResponse {
}

View File

@ -1,9 +0,0 @@
import { BaseRequest, BaseResponse } from './base'
export interface ReqGetSession extends BaseRequest {
}
export interface ResGetSession extends BaseResponse {
}

View File

@ -0,0 +1,9 @@
import { BaseRequest, BaseResponse } from './base'
export interface ReqSetCookie extends BaseRequest {
}
export interface ResSetCookie extends BaseResponse {
}

View File

@ -0,0 +1,9 @@
import { BaseRequest, BaseResponse } from './base'
export interface ReqSetSession extends BaseRequest {
}
export interface ResSetSession extends BaseResponse {
}

View File

@ -1,9 +1,10 @@
import { BaseRequest, BaseResponse } from './base' import { BaseRequest, BaseResponse } from './base';
export interface ReqTest extends BaseRequest { export interface ReqTest extends BaseRequest {
} }
export interface ResTest extends BaseResponse { export interface ResTest extends BaseResponse {
// From Session
testSession?: string
} }

View File

@ -1,9 +1,12 @@
export interface BaseRequest { export interface BaseRequest {
__session?: { [key: string]: any }; __cookie?: Cookie;
__cookie?: { [key: string]: any };
} }
export interface BaseResponse { export interface BaseResponse {
__session?: { [key: string]: any }; __cookie?: Cookie;
__cookie?: { [key: string]: any }; }
export interface Cookie {
sessionId?: string,
[key: string]: any
} }

View File

@ -1,7 +1,7 @@
import { ServiceProto } from 'tsrpc-proto'; import { ServiceProto } from 'tsrpc-proto';
import { ReqClear, ResClear } from './PtlClear'; import { ReqClear, ResClear } from './PtlClear';
import { ReqGetCookie, ResGetCookie } from './PtlGetCookie'; import { ReqSetCookie, ResSetCookie } from './PtlSetCookie';
import { ReqGetSession, ResGetSession } from './PtlGetSession'; import { ReqSetSession, ResSetSession } from './PtlSetSession';
import { ReqTest, ResTest } from './PtlTest'; import { ReqTest, ResTest } from './PtlTest';
export interface ServiceType { export interface ServiceType {
@ -10,13 +10,13 @@ export interface ServiceType {
req: ReqClear, req: ReqClear,
res: ResClear res: ResClear
}, },
"GetCookie": { "SetCookie": {
req: ReqGetCookie, req: ReqSetCookie,
res: ResGetCookie res: ResSetCookie
}, },
"GetSession": { "SetSession": {
req: ReqGetSession, req: ReqSetSession,
res: ResGetSession res: ResSetSession
}, },
"Test": { "Test": {
req: ReqTest, req: ReqTest,
@ -29,25 +29,24 @@ export interface ServiceType {
} }
export const serviceProto: ServiceProto<ServiceType> = { export const serviceProto: ServiceProto<ServiceType> = {
"version": 3,
"services": [ "services": [
{ {
"id": 3, "id": 0,
"name": "Clear", "name": "Clear",
"type": "api" "type": "api"
}, },
{
"id": 0,
"name": "GetCookie",
"type": "api"
},
{ {
"id": 1, "id": 1,
"name": "GetSession", "name": "SetCookie",
"type": "api" "type": "api"
}, },
{ {
"id": 2, "id": 2,
"name": "SetSession",
"type": "api"
},
{
"id": 3,
"name": "Test", "name": "Test",
"type": "api" "type": "api"
} }
@ -70,34 +69,34 @@ export const serviceProto: ServiceProto<ServiceType> = {
"properties": [ "properties": [
{ {
"id": 0, "id": 0,
"name": "__session",
"type": {
"type": "Interface",
"indexSignature": {
"keyType": "String",
"type": {
"type": "Any"
}
}
},
"optional": true
},
{
"id": 1,
"name": "__cookie", "name": "__cookie",
"type": { "type": {
"type": "Interface", "type": "Reference",
"indexSignature": { "target": "base/Cookie"
"keyType": "String",
"type": {
"type": "Any"
}
}
}, },
"optional": true "optional": true
} }
] ]
}, },
"base/Cookie": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "sessionId",
"type": {
"type": "String"
},
"optional": true
}
],
"indexSignature": {
"keyType": "String",
"type": {
"type": "Any"
}
}
},
"PtlClear/ResClear": { "PtlClear/ResClear": {
"type": "Interface", "type": "Interface",
"extends": [ "extends": [
@ -115,35 +114,16 @@ export const serviceProto: ServiceProto<ServiceType> = {
"properties": [ "properties": [
{ {
"id": 0, "id": 0,
"name": "__session",
"type": {
"type": "Interface",
"indexSignature": {
"keyType": "String",
"type": {
"type": "Any"
}
}
},
"optional": true
},
{
"id": 1,
"name": "__cookie", "name": "__cookie",
"type": { "type": {
"type": "Interface", "type": "Reference",
"indexSignature": { "target": "base/Cookie"
"keyType": "String",
"type": {
"type": "Any"
}
}
}, },
"optional": true "optional": true
} }
] ]
}, },
"PtlGetCookie/ReqGetCookie": { "PtlSetCookie/ReqSetCookie": {
"type": "Interface", "type": "Interface",
"extends": [ "extends": [
{ {
@ -155,7 +135,7 @@ export const serviceProto: ServiceProto<ServiceType> = {
} }
] ]
}, },
"PtlGetCookie/ResGetCookie": { "PtlSetCookie/ResSetCookie": {
"type": "Interface", "type": "Interface",
"extends": [ "extends": [
{ {
@ -167,7 +147,7 @@ export const serviceProto: ServiceProto<ServiceType> = {
} }
] ]
}, },
"PtlGetSession/ReqGetSession": { "PtlSetSession/ReqSetSession": {
"type": "Interface", "type": "Interface",
"extends": [ "extends": [
{ {
@ -179,7 +159,7 @@ export const serviceProto: ServiceProto<ServiceType> = {
} }
] ]
}, },
"PtlGetSession/ResGetSession": { "PtlSetSession/ResSetSession": {
"type": "Interface", "type": "Interface",
"extends": [ "extends": [
{ {
@ -213,6 +193,16 @@ export const serviceProto: ServiceProto<ServiceType> = {
"target": "base/BaseResponse" "target": "base/BaseResponse"
} }
} }
],
"properties": [
{
"id": 0,
"name": "testSession",
"type": {
"type": "String"
},
"optional": true
}
] ]
} }
} }

View File

@ -15,8 +15,8 @@
<div class="buttons"> <div class="buttons">
<button id="btnTest">Test</button> <button id="btnTest">Test</button>
<button id="btnClear">Clear</button> <button id="btnClear">Clear</button>
<button id="btnGetSession">Get Session</button> <button id="btnSetSession">Set Session</button>
<button id="btnGetCookie">Get Cookie</button> <button id="btnSetCookie">Set Cookie</button>
</div> </div>
<h2>API Request</h2> <h2>API Request</h2>

View File

@ -1,5 +1,5 @@
import { HttpClient } from 'tsrpc-browser'; import { HttpClient } from 'tsrpc-browser';
import { enableSessionAndCookie } from './models/enableSessionAndCookie'; import { enableCookie } from './models/enableCookie';
import { showReqAndRes } from './models/showReqAndRes'; import { showReqAndRes } from './models/showReqAndRes';
import { serviceProto } from './shared/protocols/serviceProto'; import { serviceProto } from './shared/protocols/serviceProto';
@ -10,7 +10,7 @@ let client = new HttpClient(serviceProto, {
}); });
// Session and Cookie // Session and Cookie
enableSessionAndCookie(client); enableCookie(client);
// Show Req and Return to View // Show Req and Return to View
showReqAndRes(client); showReqAndRes(client);
@ -23,9 +23,9 @@ $('#btnTest').onclick = () => {
$('#btnClear').onclick = () => { $('#btnClear').onclick = () => {
client.callApi('Clear', {}); client.callApi('Clear', {});
}; };
$('#btnGetCookie').onclick = () => { $('#btnSetCookie').onclick = () => {
client.callApi('GetCookie', {}); client.callApi('SetCookie', {});
}; };
$('#btnGetSession').onclick = () => { $('#btnSetSession').onclick = () => {
client.callApi('GetSession', {}); client.callApi('SetSession', {});
}; };

View File

@ -1,19 +1,13 @@
import { HttpClient } from "tsrpc-browser"; import { HttpClient } from "tsrpc-browser";
const CookieStorageKey = '__MY_COOKIE__'; const CookieStorageKey = '__MY_COOKIE__';
const SessionStorageKey = '__MY_SESSION__';
export function enableSessionAndCookie(client: HttpClient<any>) { export function enableCookie(client: HttpClient<any>) {
// Send // Send
client.flows.preCallApiFlow.push(v => { client.flows.preCallApiFlow.push(v => {
// Auto get __cookie from localStorage // Auto get __cookie from localStorage
let cookieStr = localStorage.getItem(CookieStorageKey); let cookieStr = localStorage.getItem(CookieStorageKey);
v.req.__cookie = cookieStr ? JSON.parse(cookieStr) : undefined; 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 v;
}) })
@ -24,10 +18,6 @@ export function enableSessionAndCookie(client: HttpClient<any>) {
if (v.return.res.__cookie) { if (v.return.res.__cookie) {
localStorage.setItem(CookieStorageKey, JSON.stringify(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; return v;

View File

@ -1,7 +1,13 @@
import { HttpClient } from "tsrpc-browser"; import { HttpClient } from "tsrpc-browser";
export function showReqAndRes(client: HttpClient<any>) { export function showReqAndRes(client: HttpClient<any>) {
// Send // Clear when send
client.flows.preCallApiFlow.push(v => {
document.querySelector('.apiReq')!.innerHTML = '';
document.querySelector('.apiReturn')!.innerHTML = '';
return v;
});
// Ouput when recv
client.flows.postApiReturnFlow.push(v => { client.flows.postApiReturnFlow.push(v => {
(document.querySelector('.apiReq') as HTMLElement).innerText = 'callApi: ' + v.apiName + '\n\n' + JSON.stringify(v.req, null, 2); (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); (document.querySelector('.apiReturn') as HTMLElement).innerText = JSON.stringify(v.return, null, 2);

View File

@ -1,9 +0,0 @@
import { BaseRequest, BaseResponse } from './base'
export interface ReqGetCookie extends BaseRequest {
}
export interface ResGetCookie extends BaseResponse {
}

View File

@ -1,9 +0,0 @@
import { BaseRequest, BaseResponse } from './base'
export interface ReqGetSession extends BaseRequest {
}
export interface ResGetSession extends BaseResponse {
}

View File

@ -0,0 +1,9 @@
import { BaseRequest, BaseResponse } from './base'
export interface ReqSetCookie extends BaseRequest {
}
export interface ResSetCookie extends BaseResponse {
}

View File

@ -0,0 +1,9 @@
import { BaseRequest, BaseResponse } from './base'
export interface ReqSetSession extends BaseRequest {
}
export interface ResSetSession extends BaseResponse {
}

View File

@ -1,9 +1,10 @@
import { BaseRequest, BaseResponse } from './base' import { BaseRequest, BaseResponse } from './base';
export interface ReqTest extends BaseRequest { export interface ReqTest extends BaseRequest {
} }
export interface ResTest extends BaseResponse { export interface ResTest extends BaseResponse {
// From Session
testSession?: string
} }

View File

@ -1,9 +1,12 @@
export interface BaseRequest { export interface BaseRequest {
__session?: { [key: string]: any }; __cookie?: Cookie;
__cookie?: { [key: string]: any };
} }
export interface BaseResponse { export interface BaseResponse {
__session?: { [key: string]: any }; __cookie?: Cookie;
__cookie?: { [key: string]: any }; }
export interface Cookie {
sessionId?: string,
[key: string]: any
} }

View File

@ -1,7 +1,7 @@
import { ServiceProto } from 'tsrpc-proto'; import { ServiceProto } from 'tsrpc-proto';
import { ReqClear, ResClear } from './PtlClear'; import { ReqClear, ResClear } from './PtlClear';
import { ReqGetCookie, ResGetCookie } from './PtlGetCookie'; import { ReqSetCookie, ResSetCookie } from './PtlSetCookie';
import { ReqGetSession, ResGetSession } from './PtlGetSession'; import { ReqSetSession, ResSetSession } from './PtlSetSession';
import { ReqTest, ResTest } from './PtlTest'; import { ReqTest, ResTest } from './PtlTest';
export interface ServiceType { export interface ServiceType {
@ -10,13 +10,13 @@ export interface ServiceType {
req: ReqClear, req: ReqClear,
res: ResClear res: ResClear
}, },
"GetCookie": { "SetCookie": {
req: ReqGetCookie, req: ReqSetCookie,
res: ResGetCookie res: ResSetCookie
}, },
"GetSession": { "SetSession": {
req: ReqGetSession, req: ReqSetSession,
res: ResGetSession res: ResSetSession
}, },
"Test": { "Test": {
req: ReqTest, req: ReqTest,
@ -29,25 +29,24 @@ export interface ServiceType {
} }
export const serviceProto: ServiceProto<ServiceType> = { export const serviceProto: ServiceProto<ServiceType> = {
"version": 3,
"services": [ "services": [
{ {
"id": 3, "id": 0,
"name": "Clear", "name": "Clear",
"type": "api" "type": "api"
}, },
{
"id": 0,
"name": "GetCookie",
"type": "api"
},
{ {
"id": 1, "id": 1,
"name": "GetSession", "name": "SetCookie",
"type": "api" "type": "api"
}, },
{ {
"id": 2, "id": 2,
"name": "SetSession",
"type": "api"
},
{
"id": 3,
"name": "Test", "name": "Test",
"type": "api" "type": "api"
} }
@ -70,34 +69,34 @@ export const serviceProto: ServiceProto<ServiceType> = {
"properties": [ "properties": [
{ {
"id": 0, "id": 0,
"name": "__session",
"type": {
"type": "Interface",
"indexSignature": {
"keyType": "String",
"type": {
"type": "Any"
}
}
},
"optional": true
},
{
"id": 1,
"name": "__cookie", "name": "__cookie",
"type": { "type": {
"type": "Interface", "type": "Reference",
"indexSignature": { "target": "base/Cookie"
"keyType": "String",
"type": {
"type": "Any"
}
}
}, },
"optional": true "optional": true
} }
] ]
}, },
"base/Cookie": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "sessionId",
"type": {
"type": "String"
},
"optional": true
}
],
"indexSignature": {
"keyType": "String",
"type": {
"type": "Any"
}
}
},
"PtlClear/ResClear": { "PtlClear/ResClear": {
"type": "Interface", "type": "Interface",
"extends": [ "extends": [
@ -115,35 +114,16 @@ export const serviceProto: ServiceProto<ServiceType> = {
"properties": [ "properties": [
{ {
"id": 0, "id": 0,
"name": "__session",
"type": {
"type": "Interface",
"indexSignature": {
"keyType": "String",
"type": {
"type": "Any"
}
}
},
"optional": true
},
{
"id": 1,
"name": "__cookie", "name": "__cookie",
"type": { "type": {
"type": "Interface", "type": "Reference",
"indexSignature": { "target": "base/Cookie"
"keyType": "String",
"type": {
"type": "Any"
}
}
}, },
"optional": true "optional": true
} }
] ]
}, },
"PtlGetCookie/ReqGetCookie": { "PtlSetCookie/ReqSetCookie": {
"type": "Interface", "type": "Interface",
"extends": [ "extends": [
{ {
@ -155,7 +135,7 @@ export const serviceProto: ServiceProto<ServiceType> = {
} }
] ]
}, },
"PtlGetCookie/ResGetCookie": { "PtlSetCookie/ResSetCookie": {
"type": "Interface", "type": "Interface",
"extends": [ "extends": [
{ {
@ -167,7 +147,7 @@ export const serviceProto: ServiceProto<ServiceType> = {
} }
] ]
}, },
"PtlGetSession/ReqGetSession": { "PtlSetSession/ReqSetSession": {
"type": "Interface", "type": "Interface",
"extends": [ "extends": [
{ {
@ -179,7 +159,7 @@ export const serviceProto: ServiceProto<ServiceType> = {
} }
] ]
}, },
"PtlGetSession/ResGetSession": { "PtlSetSession/ResSetSession": {
"type": "Interface", "type": "Interface",
"extends": [ "extends": [
{ {
@ -213,6 +193,16 @@ export const serviceProto: ServiceProto<ServiceType> = {
"target": "base/BaseResponse" "target": "base/BaseResponse"
} }
} }
],
"properties": [
{
"id": 0,
"name": "testSession",
"type": {
"type": "String"
},
"optional": true
}
] ]
} }
} }