GithubHelp home page GithubHelp logo

chefbingbong / libjrpc Goto Github PK

View Code? Open in Web Editor NEW

This project forked from danielgary/libjrpc

0.0 0.0 0.0 100 KB

Transport Agnostic JSON RPC Library

License: MIT License

JavaScript 19.96% TypeScript 80.04%

libjrpc's Introduction

libjrpc

Transport Agnostic JSON RPC Library

The goal of libjrpc is to provide a JSON RPC Server implementation that can run in any Node environment

Here is a basic example of it running in an express-like environment

import { createJRPCServer } from 'libjrpc';
const jrpcServer = createJRPCServer({
  'hello_world': (args, context) => {
    return 'Hello, world!'
  }
})

app.post('/api/jsonrpc', async (req, res) => {
  const response = await jrpcServer.handleRequest(req.body, context);
  res.json({data: response})
})

Here's a handy JSON RPC hook for react:

import { useCallback, useState } from 'react'

export interface UseProcedureResult<TResult> {
	error: Error | null
	result: TResult | null
}

export interface UseProcedureHookResult<TParams, TResult> extends UseProcedureResult<TResult> {
	loading: boolean
	// eslint-disable-next-line no-unused-vars
	execute: (params: TParams, headers?: Record<string, string>) => Promise<UseProcedureResult<TResult>>
}

export const useProcedure = <TParams, TResult>(methodName: string): UseProcedureHookResult<TParams, TResult> => {
	const [loading, setLoading] = useState(false)
	const [error, setError] = useState<Error | null>(null)
	const [result, setResult] = useState<TResult | null>(null)

	const execute = useCallback(
		async (params: TParams, headers: Record<string, string> = {}) => {
			const id = new Date().getTime()
			const body = {
				id,
				jsonrpc: '2.0',
				method: methodName,
				params
			}

			headers['Content-Type'] = 'application/json'

			setError(null)
			setLoading(true)

			try {
				const response = await fetch(`/api/jsonrpc`, { body: JSON.stringify(body), headers, method: 'POST' })
				const parsedResponse = await response.json()

				if (parsedResponse.error) {
					const error: Error = { message: parsedResponse.error.message, name: `JRPCError` }
					setError(error)
					return { error, result: null }
				} else {
					const result = parsedResponse.result as TResult
					setResult(result)
					return { error: null, result }
				}
			} catch (err) {
				setResult(null)
				setError(err)
				return { error: err, result: null }
			} finally {
				setLoading(false)
			}
		},
		[methodName, setLoading, setError, setResult]
	)

	return {
		error,
		execute,
		loading,
		result
	}
}

You can use it like this:

const {execute, loading, error, result} = useProcedure('hello_world')

return ( 
  <div>
    <button onClick={()=>{execute({})}}>Execute</button>
      Result: {result}
    </div>
)

libjrpc's People

Contributors

danielgary avatar nathanwaddell121107 avatar justinneff avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.