Skip to content

Commit

Permalink
add basic tests and simplify some code, make some api private
Browse files Browse the repository at this point in the history
  • Loading branch information
v1rtl committed Nov 7, 2022
1 parent 296ea44 commit 7bd3bd1
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 18 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
coverage*
6 changes: 5 additions & 1 deletion egg.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@
"releaseType": null,
"unstable": false,
"unlisted": false,
"files": ["README.md", "*.ts", "LICENSE"],
"files": [
"README.md",
"*.ts",
"LICENSE"
],
"ignore": [],
"checkFormat": false,
"checkTests": false,
Expand Down
6 changes: 2 additions & 4 deletions request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@ export function parseRequest(json: string): (JsonRpcRequest | 'invalid')[] | 'pa
const res: (JsonRpcRequest | 'invalid')[] = []

for (const obj of arr) {
if (typeof obj !== 'object') res.push('invalid')
else if (!obj) res.push('invalid')
else if (obj.jsonrpc !== '2.0') res.push('invalid')
else if (typeof obj.method !== 'string') res.push('invalid')
if (typeof obj !== 'object' || !obj || obj.jsonrpc !== '2.0' || typeof obj.method !== 'string')
res.push('invalid')
else res.push(obj)
}

Expand Down
17 changes: 12 additions & 5 deletions server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ export class App {
socks: Map<string, WebSocket>
methods: Map<string, (params: any[], clientId: string) => Promise<any>>
emitters: Map<string, (params: any[], emit: (data: any) => void, clientId: string) => void>
timeout: number
#timeout: number
constructor(options: RPCOptions = { path: '/' }) {
this.options = options
this.socks = new Map()
this.methods = new Map()
this.emitters = new Map()
this.timeout = options.timeout || 1000 * 60 * 60 * 24
this.#timeout = options.timeout || 1000 * 60 * 60 * 24
}
/**
* Upgrade a request to WebSocket and handle it
Expand All @@ -42,11 +42,11 @@ export class App {
this.socks.set(clientId, socket)

// Close the socket after timeout
setTimeout(() => socket.close(), this.timeout)
setTimeout(() => socket.close(), this.#timeout)

socket.onmessage = ({ data }) => {
if (typeof data === 'string') {
send(socket, this.handleRPCMethod(clientId as string, data))
send(socket, this.#handleRPCMethod(clientId as string, data))
} else if (data instanceof Uint8Array) {
console.warn('Warn: an invalid jsonrpc message was sent. Skipping.')
}
Expand Down Expand Up @@ -80,7 +80,7 @@ export class App {
* @param client client ID
* @param data Received data
*/
async handleRPCMethod(client: string, data: string) {
async #handleRPCMethod(client: string, data: string) {
const sock = this.socks.get(client)

if (!sock) return console.warn(`Warn: recieved a request from and undefined connection`)
Expand Down Expand Up @@ -151,4 +151,11 @@ export class App {
e.respondWith(this.handle(e.request))
}
}
/**
* Close the server
*/
close() {
this.httpConn?.close()
this.listener?.close()
}
}
12 changes: 4 additions & 8 deletions utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export const makeArray = <T>(val: T | T[]) => (Array.isArray(val) ? val : [val])

export function makeEncryptor(key: string) {
const textToChars = (text: string) => text.split('').map((c) => c.charCodeAt(0))
const byteHex = (n: number) => ('0' + Number(n).toString(16)).substr(-2)
const byteHex = (n: number) => ('0' + Number(n).toString(16)).substring(-2)
const applyKeyToChar = (code: number) => textToChars(key).reduce((a, b) => a ^ b, code)

function decrypt(encoded: string) {
Expand All @@ -29,14 +29,10 @@ export function lazyJSONParse(json: string): any {
}

export function delay(time: number) {
return new Promise<void>((resolve) => {
setTimeout(() => resolve(), time)
})
return new Promise<void>((resolve) => void setTimeout(() => resolve(), time))
}

export function pathsAreEqual(actual: string, expected: string | undefined) {
if (expected === '*') return true
return actual === (expected || '/')
}
export const pathsAreEqual = (actual: string, expected?: string) =>
expected === '*' ? true : actual === (expected || '/')

export const paramsEncoder = makeEncryptor('nothing-secret')
23 changes: 23 additions & 0 deletions utils_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { lazyJSONParse, pathsAreEqual } from './utils.ts'
import { assertEquals } from 'https://deno.land/std@0.162.0/testing/asserts.ts'

Deno.test('lazyJSONParse', async (it) => {
await it.step('should parse JSON like JSON.parse', () => {
assertEquals(lazyJSONParse('{ "a": "b" }'), JSON.parse('{ "a": "b" }'))
})
await it.step('should return an empty object on failed parse', () => {
assertEquals(lazyJSONParse('{ "a": "b"'), {})
})
})

Deno.test('pathsAreEqual', async (it) => {
await it.step('if expected path is asterisk, return true', () => {
assertEquals(pathsAreEqual('/hello', '*'), true)
})
await it.step('should assert equal paths', () => {
assertEquals(pathsAreEqual('/hello', '/hello'), true)
})
await it.step('if nothing is expected, default to "/"', () => {
assertEquals(pathsAreEqual('/'), true)
})
})

0 comments on commit 7bd3bd1

Please sign in to comment.