Skip to content

Instantly share code, notes, and snippets.

@oscartbeaumont
Created August 4, 2024 09:30
Show Gist options
  • Save oscartbeaumont/04071c5c4c17c3a8786c11a2fb00cdf8 to your computer and use it in GitHub Desktop.
Save oscartbeaumont/04071c5c4c17c3a8786c11a2fb00cdf8 to your computer and use it in GitHub Desktop.
rspc JS/TS impl for testing new stuff
function concatArrayBuffers(chunks: Uint8Array[]): Uint8Array {
const result = new Uint8Array(chunks.reduce((a, c) => a + c.length, 0));
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
class LineSplitter extends TransformStream<Uint8Array, Uint8Array> {
protected _buffer: Uint8Array[] = [];
constructor() {
super({
transform: (chunk, controller) => {
let index;
let rest = chunk;
while ((index = rest.indexOf(0x0a)) !== -1) {
controller.enqueue(concatArrayBuffers([...this._buffer, rest.slice(0, index + 1)]));
rest = rest.slice(index + 1);
this._buffer = [];
}
if (rest.length > 0) {
this._buffer.push(rest);
}
},
flush: (controller) => {
if (this._buffer.length > 0) {
controller.enqueue(concatArrayBuffers(this._buffer));
}
}
});
}
}
async function makeRequest(url: string) {
const resp = await fetch(url, {
headers: {
"x-rspc": "0.3.0",
"content-type": "application/json"
}
});
if (resp.headers.get("content-type") === "application/jsonl") {
const linesStream = resp.body
.pipeThrough(new LineSplitter());
const tx = new TextDecoder();
const r: any[] = [];
for await (const line of linesStream) {
r.push(JSON.parse(tx.decode(line)));
}
return "S " + JSON.stringify(r);
} else if (resp.headers.get("content-type") === "application/json") {
if (resp.status === 200) {
return "T " + await resp.text(); // `T`
} else if (resp.status > 300 && resp.status < 600) {
// TODO: We need to detect `#rspc#error` and convert it into a class.
return "TError " + await resp.text(); // `TError | RspcError`
} else {
// Error: rspc won't produce any other status code.
throw new Error("Unknown status code");
}
} else {
// Error: We have hit a Vercel checkpoint or something else.
throw new Error("Unknown content type");
}
}
console.log(await makeRequest("http://localhost:3000/rspc/version"));
console.log(await makeRequest("http://localhost:3000/rspc/error2"));
console.log(await makeRequest("http://localhost:3000/rspc/streamingNone"));
console.log(await makeRequest("http://localhost:3000/rspc/streamingError"));
console.log(await makeRequest("http://localhost:3000/rspc/streamingErrorFlip"));
console.log(await makeRequest("http://localhost:3000/rspc/streaming"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment