The postgres client/server binary protocol, implemented in TypeScript
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Stream-based parsing of PostgreSQL wire protocol messages providing a callback-based interface for handling incoming protocol data.
Main entry point for parsing PostgreSQL protocol streams. Attaches to a readable stream and calls the provided callback for each parsed message.
/**
* Parse PostgreSQL protocol messages from a stream
* @param stream - Readable stream containing protocol data
* @param callback - Function called for each parsed message
* @returns Promise that resolves when stream ends
*/
function parse(
stream: NodeJS.ReadableStream,
callback: MessageCallback
): Promise<void>;Usage Examples:
import { parse } from "pg-protocol";
// Basic stream parsing
const callback = (message) => {
switch (message.name) {
case 'dataRow':
console.log('Data row:', message);
break;
case 'commandComplete':
console.log('Command completed:', message.text);
break;
case 'error':
console.error('Database error:', message);
break;
}
};
await parse(stream, callback);The Parser class is used internally by the parse function and is not part of the public API. It provides stateful parsing with buffer management for the protocol stream.
/**
* Internal stateful PostgreSQL protocol parser
* Note: This class is not exported and is used internally by the parse function
*/
class Parser {
/**
* Create a new parser instance
* @param opts - Optional stream options
*/
constructor(opts?: StreamOptions);
/**
* Parse buffer data and call callback for each complete message
* @param buffer - Raw protocol data buffer
* @param callback - Function called for each parsed message
*/
parse(buffer: Buffer, callback: MessageCallback): void;
}
interface StreamOptions {
mode?: Mode;
}Callback function signature for handling parsed protocol messages.
/**
* Callback function for handling parsed protocol messages
* @param msg - Parsed protocol message
*/
type MessageCallback = (msg: BackendMessage) => void;Configuration options for the Parser constructor.
interface StreamOptions {
/** Data format mode - 'text' or 'binary' (binary not yet supported) */
mode?: Mode;
}The parser handles malformed protocol data by creating DatabaseError instances:
// Invalid message codes result in DatabaseError
const errorMessage = new DatabaseError(
'received invalid response: ' + code.toString(16),
length,
'error'
);The parser supports the complete PostgreSQL wire protocol including:
Install with Tessl CLI
npx tessl i tessl/npm-pg-protocol