npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@gdjiami/jsonrpc

v2.4.6

Published

JSON RPC Client

Downloads

31

Readme

JSONRPC

JSONRPC 客户端

安装

yarn add @gdjiami/jsonrpc

使用

实例化

import RPC from '@gdjiami/jsonrpc'

/**
 * 设置RPC root url
 */

const root = '/jsonrpc'
const rpc = new RPC(root)

/**
 * 设置拦截器(可选)
 */
rpc.addInterceptor(async (request, xhr, next) => {
  const token = authService.getToken()
  if (token) {
    xhr.setRequestHeader(TOKEN_HEADER, token)
  }

  try {
    // 发起请求
    return await next()
  } catch (error) {
    // 捕获错误
    const { code } = error as RequestError<any, any>
    if (code === AUTH_FAILED_CODE) {
      console.warn('会话失效')
      try {
        // refresh token
        await authService.refresh()
        // refresh successful, retry
        return await rpc.retry<any>(request)
      } catch (err) {
        console.warn('刷新token失败', err)
        throw err
      }
    }

    throw error
  }
})

// 可以添加多个拦截器。拦截器的处理原理和`koa`中间件一样

调用

async function ping(params: PingParams) {
  try {
    // 可以使用泛型变量声明:<响应类型, [请求的参数类型(可选)]>
    const res = await rpc.request<{ content: string }>('utils.ping', params)
    console.log(res.content)
  } catch (err) {
    // 在这里捕获HTTP错误,JSONRPC协议错误(通过error对象返回)
    message.error(`请求失败: ${err.message}`)
  }
}

API

constructor(root: string): 创建 JSONRPC 客户端

  • root: RPC 根路径

#request<R, P = {}>(method: string, params?: P): Promise<R>: 发起请求

  • method: 调用方法
  • params: 调用参数
  • 返回 Promise,resolved 响应结果中的 result 字段数据

如果请求失败,将抛出 RequestError<P, R>类型的错误对象, 可以这样处理错误:

import { RequestError } from '@gdjiami/jsonrpc'

async function myRequest() {
  try {
    // 可以使用泛型变量声明:<响应类型, [请求的参数类型(可选)]>
    const res = await rpc.request<{ content: string }>('utils.ping', params)
  } catch (err) {
    const { code, request, response, message } = err as RequestError<any, any>
    // 在这里捕获HTTP错误,JSONRPC协议错误(通过error对象返回)
    message.error(`请求失败: ${err.message}`)
  }
}

#addInterceptor(i: RPCInterceptor): 添加拦截器

  • RPCInterceptor: 拦截器方法
/**
 * 拦截器方法
 */
export type RPCInterceptor = (
  /**
   * JSONRPC 请求对象
   */
  request: JSONRPCRequest<any>,
  /**
   * XMLHttpRequest 对象,可以对ajax请求进行预处理,比如添加Header
   */
  xhr: XMLHttpRequest,
  /**
   * 调用下一个拦截器,如果是最后一个拦截器则发起请求。
   * 返回一个Promise,可以在响应的内容进行操作或后处理
   */
  next: () => Promise<JSONRPCResponse<any>>,
) => Promise<JSONRPCResponse<any>>

/**
 * JSON RPC 请求对象
 */

export interface JSONRPCRequest<T> {
  jsonrpc: '2.0'
  method: string
  id: string | number
  params?: T
}

/**
 * JSON RPC 响应对象
 */

export interface JSONRPCResponse<T> {
  jsonrpc: '2.0'
  id: string | number
  error?: JSONRPCError
  result: T
}

/**
 * JSON RPC 错误对象
 */

export interface JSONRPCError {
  code: number
  message: string
  data?: any
}

#retry<R, P = {}>(request: JSONRPCRequest<P>): Promise<R>

重新发起请求, 主要用于拦截器

参考

JSONRPC 协议

License

This project is licensed under the terms of the MIT license.