Skip to content

Commit

Permalink
rename MethodSet to Methods & 100% cov
Browse files Browse the repository at this point in the history
  • Loading branch information
YieldRay committed Jan 27, 2024
1 parent 6d498ee commit 263bc2c
Show file tree
Hide file tree
Showing 9 changed files with 250 additions and 175 deletions.
95 changes: 29 additions & 66 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,92 +8,55 @@ A strictly typed json-rpc(2.0) implementation, zero dependency, minimal abstract

> Specification <https://www.jsonrpc.org/specification>
```ts
const methodSet = {
upper: (str: string) => str.toUpperCase(),
lower: (str: string) => str.toLowerCase(),
plus: ([a, b]: [number, number]) => a + b,
minus: ([a, b]: [number, number]) => a - b,
}

// initialize all methods with the constructor
const server = new JSONRPCServer(methodSet)

// or add methods manually
const server = new JSONRPCServer<typeof methodSet>()
server.setMethod('upper', methodSet.upper)
server.setMethod('lower', methodSet.lower)
server.setMethod('plus', methodSet.plus)
server.setMethod('minus', methodSet.minus)

// (optional) provide a generic parameter to enable ts check
const client = new JSONRPCClient<typeof methodSet>((json) =>
server.process(json)
)

// request, Notification and batch are always async
assertEquals(await client.request('upper', 'hello'), 'HELLO')

assertEquals(
await client.batch(
client.createRequest('upper', 'nihao'),
// Notification does not have response, even when response errors
client.createNotification('upper'),
client.createRequest('upper', 'shijie'),
client.createRequest('plus', [1, 1]),
),
[
{
status: 'fulfilled',
value: 'NIHAO',
},
{
status: 'fulfilled',
value: 'SHIJIE',
},
{
status: 'fulfilled',
value: 2,
},
],
)
```

Example to use the client

```ts
const client = new JSONRPCClient((json) =>
const requestForResponse = (json: string) =>
fetch('http://localhost:6800/jsonrpc', {
method: 'POST',
body: json,
}).then((res) => res.text())
)

const aria2cMethods = await client.request('system.listMethods')
const client = new JSONRPCClient<{
'aria2.addUri': (
urls: string[],
options?: object,
position?: number,
) => string
'aria2.remove': (gid: string) => string
'system.listMethods': () => string[]
}>(requestForResponse)

const resultGid: string = await client.request('aria2.addUri', [
['https://example.net/index.html'],
{},
0,
])
```

Example to use the server

```ts
const server = new JSONRPCServer()
const server = new JSONRPCServer({
upper: (str: string) => str.toUpperCase(),
lower: (str: string) => str.toLowerCase(),
plus: ([a, b]: [number, number]) => a + b,
minus: ([a, b]: [number, number]) => a - b,
})

// or:
server.setMethod('trim', (str: string) => str.trim())
server.setMethod('trimStart', (str: string) => str.trimStart())
server.setMethod('trimEnd', (str: string) => str.trimEnd())

const httpServer = Deno.serve(
async (request) => {
const url = new URL(request.url)
if (url.pathname === '/jsonrpc') {
return new Response(
// server.process() accept string and returns Promise<string>
await server.process(await request.text()),
{
headers: { 'content-type': 'application/json' },
},
)
}
return new Response('404', { status: 404 })
// server.handleRequest() accept string and returns Promise<string>
const jsonString = await server.handleRequest(await request.text())

return new Response(jsonString, {
headers: { 'content-type': 'application/json' },
})
},
)
```
Expand Down
2 changes: 1 addition & 1 deletion deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"noImplicitOverride": true
},
"imports": {
"std/": "https://deno.land/std@0.209.0/"
"std/": "https://deno.land/std@0.213.0/"
},
"tasks": {
"lint": "deno lint",
Expand Down
34 changes: 33 additions & 1 deletion deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 41 additions & 0 deletions src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,47 @@ Deno.test('client/JSONRPCClientParseError', async () => {
).catch((e) => e),
JSONRPCClientParseError,
)

client = new JSONRPCClient(() =>
JSON.stringify(
{
jsonrpc: '2.0',
id: null,
error: {
code: 0,
message: 'ERR_MSG',
},
},
)
)

assertEquals(
await client.batch(
client.createRequest('foo1'),
client.createRequest('foo2'),
client.createRequest('foo3'),
).catch((e) => e.message),
'ERR_MSG',
)

client = new JSONRPCClient(() =>
JSON.stringify(
{
jsonrpc: '2.0',
id: null,
result: 'wrong server',
},
)
)

assertInstanceOf(
await client.batch(
client.createRequest('foo1'),
client.createRequest('foo2'),
client.createRequest('foo3'),
).catch((e) => e),
JSONRPCClientParseError,
)
})

Deno.test({
Expand Down
Loading

0 comments on commit 263bc2c

Please sign in to comment.