前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go+gRPC-Gateway(V2) 微服务实战,小程序登录鉴权服务(六):客户端基础库 TS 实战

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

作者头像
为少
发布2021-05-27 18:55:49
8240
发布2021-05-27 18:55:49
举报
文章被收录于专栏:黑客下午茶

小程序登录鉴权服务,客户端底层 SDK,登录鉴权、业务请求、鉴权重试模块 Typescript 实战。

系列

  1. 云原生 API 网关,gRPC-Gateway V2 初探
  2. Go + gRPC-Gateway(V2) 构建微服务实战系列,小程序登录鉴权服务:第一篇
  3. Go + gRPC-Gateway(V2) 构建微服务实战系列,小程序登录鉴权服务:第二篇
  4. Go + gRPC-Gateway(V2) 构建微服务实战系列,小程序登录鉴权服务(三):RSA(RS512) 签名 JWT
  5. Go+gRPC-Gateway(V2) 微服务实战,小程序登录鉴权服务(四):自动生成 API TS 类型
  6. Go+gRPC-Gateway(V2) 微服务实战,小程序登录鉴权服务(五):鉴权 gRPC-Interceptor 拦截器实战

Demo:

  • https://github.com/Hacker-Linner/go-grpc-gateway-v2-microservice

前端底层初步搭建(SDK)

新建 client/miniprogram/service/sdk.ts 文件,来初步搭建一下我们前端的底层公共设施。

定义一个 SDK namespace

代码语言:javascript
复制
export namespace SDK {
    
}

定义相关常量 & Interface

代码语言:javascript
复制
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 形式

代码语言:javascript
复制
export function wxLogin(): Promise<WechatMiniprogram.LoginSuccessCallbackResult> {
        return new Promise((resolve, reject) => {
            wx.login({
                success: resolve,
                fail: reject,
            })
        })
    }

请求公共逻辑 wx.request 编写

代码语言:javascript
复制
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)编写

代码语言:javascript
复制
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
}

业务请求自动重试模块编写

代码语言:javascript
复制
 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

代码语言:javascript
复制
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
    • https://github.com/grpc-ecosystem/go-grpc-middleware
  • Demo: go-grpc-gateway-v2-microservice
    • https://github.com/Hacker-Linner/go-grpc-gateway-v2-microservice
  • gRPC-Gateway
    • https://github.com/grpc-ecosystem/grpc-gateway
  • gRPC-Gateway Docs
    • https://grpc-ecosystem.github.io/grpc-gateway
  • API Security : API key is dead..Long live Distributed Token by value
    • https://www.linkedin.com/pulse/api-security-key-deadlong-live-distributed-token-value-joseph-george
代码语言:javascript
复制
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-04-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 黑客下午茶 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 系列
  • 前端底层初步搭建(SDK)
    • 定义一个 SDK namespace
      • 定义相关常量 & Interface
        • wx.login 改写成 Promise 形式
          • 请求公共逻辑 wx.request 编写
            • 登录模块(login)编写
              • 业务请求自动重试模块编写
              • Todo Service
                • 创建一个 Todo
                • Refs
                相关产品与服务
                云开发 CloudBase
                云开发(Tencent CloudBase,TCB)是腾讯云提供的云原生一体化开发环境和工具平台,为200万+企业和开发者提供高可用、自动弹性扩缩的后端云服务,可用于云端一体化开发多种端应用(小程序、公众号、Web 应用等),避免了应用开发过程中繁琐的服务器搭建及运维,开发者可以专注于业务逻辑的实现,开发门槛更低,效率更高。
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档