Go+gRPC-Gateway(V2) 微服务实战,小程序登录鉴权服务(六):客户端基础库 TS 实战

小程序登录鉴权服务,客户端底层 SDK,登录鉴权、业务请求、鉴权重试模块 Typescript 实战。
系列
- 云原生 API 网关,gRPC-Gateway V2 初探
- Go + gRPC-Gateway(V2) 构建微服务实战系列,小程序登录鉴权服务:第一篇
- Go + gRPC-Gateway(V2) 构建微服务实战系列,小程序登录鉴权服务:第二篇
- Go + gRPC-Gateway(V2) 构建微服务实战系列,小程序登录鉴权服务(三):RSA(RS512) 签名 JWT
- Go+gRPC-Gateway(V2) 微服务实战,小程序登录鉴权服务(四):自动生成 API TS 类型
- Go+gRPC-Gateway(V2) 微服务实战,小程序登录鉴权服务(五):鉴权 gRPC-Interceptor 拦截器实战
Demo: go-grpc-gateway-v2-microservice
前端底层初步搭建(SDK)
新建 client/miniprogram/service/sdk.ts 文件,来初步搭建一下我们前端的底层公共设施。
定义一个 SDK namespace
export namespace SDK {
}
定义相关常量 & Interface
const serverAddr = 'http://localhost:8080'
const AUTH_ERR= 'AUTH_ERR'
const authData = {
token: '',
expiryMs: 0
}
interface RequestOption<REQ, RES> {
method: 'GET'|'PUT'|'POST'|'DELETE'
path: string
data: REQ
respMarshaller: (r: object)=>RES
}
interface AuthOption {
attachAuthHeader: boolean
retryOnAuthError: boolean
}
这里主要根据当前需求,做了如下事情:
- 抽出服务器地址
serverAddr - 定义一个授权失败
401常量 token相关暂时存到内存中- 定义客户端
wx.request所必须的参数类型 - 控制授权请求相关逻辑(是否附加
Auth Header& 重试等)
wx.login 改写成 Promise 形式
export function wxLogin(): Promise<WechatMiniprogram.LoginSuccessCallbackResult> {
return new Promise((resolve, reject) => {
wx.login({
success: resolve,
fail: reject,
})
})
}
请求公共逻辑 wx.request 编写
export function sendRequest<REQ, RES>(o: RequestOption<REQ, RES>, a: AuthOption): Promise<RES> {
const authOpt = a || {
attachAuthHeader: true,
}
return new Promise((resolve, reject) => {
const header: Record<string, any> = {}
if (authOpt.attachAuthHeader) {
if (authData.token && authData.expiryMs >= Date.now()) {
header.authorization = 'Bearer '+ authData.token
} else {
reject(AUTH_ERR)
return
}
}
wx.request({
url: serverAddr + o.path,
method: o.method,
data: o.data,
header,
success: res => {
if(res.statusCode === 401) {
reject(AUTH_ERR)
} else if (res.statusCode >= 400) {
reject(res)
} else {
resolve(
o.respMarshaller(
camelcaseKeys(res.data as object, { deep: true }),
)
)
}
},
fail: reject
})
})
}
登录模块(login)编写
export async function login() {
if (authData.token && authData.expiryMs >= Date.now()) {
return
}
const wxResp = await wxLogin()
const reqTimeMs = Date.now()
const resp = await sendRequest<auth.v1.ILoginRequest, auth.v1.ILoginResponse>({
method: "POST",
path: "/v1/auth/login",
data: {
code: wxResp.code,
},
respMarshaller: auth.v1.LoginResponse.fromObject
}, {
attachAuthHeader: false,
retryOnAuthError: false,
})
authData.token = resp.accessToken!
authData.expiryMs = reqTimeMs + resp.expiresIn! * 1000
}
业务请求自动重试模块编写
export async function sendRequestWithAuthRetry<REQ, RES>(o: RequestOption<REQ, RES>, a?: AuthOption): Promise<RES> {
const authOpt = a || {
attachAuthHeader: true,
retryOnAuthError: true,
}
try {
await login()
return sendRequest(o, authOpt)
} catch(err) {
if(err === AUTH_ERR && authOpt.retryOnAuthError) {
authData.token = ''
authData.expiryMs = 0
return sendRequestWithAuthRetry(o, {
attachAuthHeader: authOpt.attachAuthHeader,
retryOnAuthError: false
})
} else {
throw err
}
}
}
Todo Service
客户端具体服务层,这里是 Todo 这个服务。
我们新建一个文件控制客户端相关逻辑:client/miniprogram/service/todo.ts
创建一个 Todo
export namespace TodoService {
export function CreateTodo(req: todo.v1.ICreateTodoRequest): Promise<todo.v1.ICreateTodoResponse>{
return SDK.sendRequestWithAuthRetry({
method: "POST",
path: "/v1/todo",
data: req,
respMarshaller: todo.v1.CreateTodoResponse.fromObject
})
}
}
低层弄好后,上层堆业务就爽很多了。
Refs
- grpc-ecosystem/go-grpc-middleware
- API Security : API key is dead..Long live Distributed Token by value
- Demo: go-grpc-gateway-v2-microservice
- gRPC-Gateway
- gRPC-Gateway Docs
我是为少
微信:uuhells123
公众号:黑客下午茶
加我微信(互相学习交流),关注公众号(获取更多学习资料~)
Go+gRPC-Gateway(V2) 微服务实战,小程序登录鉴权服务(六):客户端基础库 TS 实战的更多相关文章
- Go+gRPC-Gateway(V2) 微服务实战,小程序登录鉴权服务(五):鉴权 gRPC-Interceptor 拦截器实战
拦截器(gRPC-Interceptor)类似于 Gin 中间件(Middleware),让你在真正调用 RPC 服务前,进行身份认证.参数校验.限流等通用操作. 系列 云原生 API 网关,gRPC ...
- Go+gRPC-Gateway(V2) 微服务实战,小程序登录鉴权服务(四):客户端强类型约束,自动生成 API TS 类型定义
系列 云原生 API 网关,gRPC-Gateway V2 初探 Go + gRPC-Gateway(V2) 构建微服务实战系列,小程序登录鉴权服务:第一篇 Go + gRPC-Gateway(V2) ...
- Go + gRPC-Gateway(V2) 构建微服务实战系列,小程序登录鉴权服务:第一篇(内附开发 demo)
简介 小程序可以通过微信官方提供的登录能力方便地获取微信提供的用户身份标识,快速建立小程序内的用户体系. 系列 云原生 API 网关,gRPC-Gateway V2 初探 业务流程 官方开发接入文档 ...
- 微信小程序登录鉴权流程图
- Flask与微信小程序登录(后端)
开发微信小程序时,接入小程序的授权登录可以快速实现用户注册登录的步骤,是快速建立用户体系的重要一步.这篇文章将介绍 python + flask + 微信小程序实现用户快速注册登录方案(本文主要进行后 ...
- 微慕WordPress小程序增强版
2017年1月9日,张小龙在2017微信公开课Pro上发布的微信小程序正式上线.在过去的2年多的时间里,微信小程序领头,各大互联网平台也不甘落后,陆续推出自己的小程序.2018年7月4日,百度智能小程 ...
- JeeWx捷微3.1小程序版本发布,支持微信公众号,微信企业号,支付窗——JAVA版开源微信管家
支持小程序,JeeWx捷微3.1小程序版本发布^_^ JeeWx捷微V3.1——多触点小程序版本管理平台(支持微信公众号,微信企业号,支付窗) JeeWx捷微V3.1.0版本紧跟微信小程序更新,在 ...
- JAVA版开源微信管家—JeeWx捷微3.1小程序版本发布,支持微信公众号,微信企业号,支付窗
支持小程序,JeeWx捷微3.1小程序版本发布^_^ JeeWx捷微V3.1--多触点小程序版本管理平台(支持微信公众号,微信企业号,支付窗) JeeWx捷微V3.1.0版本紧跟微信小程序更新,在原有 ...
- 小程序server-3-搭建WebSocket 服务
小程序server-3-搭建WebSocket 服务: 1.安装 Node 模块 使用 ws 模块来在服务器上支持 WebSocket 协议,下面使用 NPM 来安装: cd /var/www/wxp ...
随机推荐
- IDEA中引用不到HttpServlet的解决方案
原文链接:https://blog.csdn.net/xiaozaizi666/article/details/87805564
- BSOJ 1562 【堆练习】丑数3576
Description 丑数是指素因子都在集合{2,3,5,7}内的整数,第一个丑数是1. 现在输入n(n<=4000),输出第n个丑数. Input 输入文件仅一行为一个整数n. Output ...
- KnowRbao_uni-app
uni-app开发项目模板 主要的代码如下: pages.json 这里是添加页面的路径代码还可以设置标题: { "pages" : [ //pages数组中第一项表示应用启动页, ...
- Centos7.7下安装Python3.7 并兼容python2.7
前言 1.首先来看一下系统版本 [root@python3 ~]# cat /etc/redhat-release CentOS Linux release 7.7.1810 (Core) 2.更新一 ...
- 微信小程序去除页面滚动条
::-webkit-scrollbar { width: 0; height: 0; color: transparent; display: none; } 父级元素(滚动的元素) width:10 ...
- LeetCode-二叉搜索树的第k大节点
二叉搜索树的第k大节点 LeetCode-面试题54 需要充分了解二叉搜索树的性质. 利用中序遍历的思想,采用相反的思想:先遍历右节点再遍历左节点. /** * 给定一棵二叉搜索树,请找出其中第k大的 ...
- MySql数据库列表数据分页查询、全文检索API零代码实现
数据条件查询和分页 前面文档主要介绍了元数据配置,包括表单定义和表关系管理,以及表单数据的录入,本文主要介绍数据查询和分页在crudapi中的实现. 概要 数据查询API 数据查询主要是指按照输入条件 ...
- 【Arduino学习笔记03】面包板基础知识
终端带 这里有一块面包板,它后面的黏贴纸被撕去了.你可以看到很多在底部的平行金属条. 金属条的结构:金属条的顶部有一个小夹子.这些夹子能将一条导线或某个部件的引脚固定在塑料洞上,使它们放置在适当的位置 ...
- Codeforces Round #699 (Div. 2)
A Space Navigation #include <bits/stdc++.h> using namespace std; typedef long long LL; #define ...
- 给出镜像FreeBSD 基本要求
硬盘 ports 500G update 500G portsnap 500G pkg arm64 amd64 i386 11-12-13 4TB 网络流量一个月专线大概2w RMB CPU 内存 其 ...