gcf-common-lib
v0.49.0
Published
Common helpers for Google Cloud Functions: Pub/Sub publishing, Mongo helpers, and utilities for Node 20+ (TypeScript).
Readme
gcf-common-lib
Common helpers for Google Cloud Functions (GCF) and Node services:
- Orchestrate handlers and conditional response publishing via Pub/Sub or AMQP (RabbitMQ).
- Utilities: time helpers (ms/sec), Excel A1 conversions, safeJsonParse, simple delay/timeout.
- Helpers for AMQP and MongoDB lifecycles.
This library targets Node >= 20 and TypeScript. It is designed to be consumed by TS-aware builds or transpiled output.
Installation
npm i gcf-common-libQuick start
Process an event without network I/O
Pass a payload without topic, exchange, or queue to avoid publishing in unit tests or offline flows.
import { GcfCommon } from 'gcf-common-lib';
export async function handler(payload: any) {
return { ok: 1 };
}
// Example payload: Pub/Sub-like message without routing attributes
const payload = {
event: { '@type': 'type.googleapis.com/google.pubsub.v1.PubsubMessage', json: { hello: 'world' }, attributes: {} },
context: undefined,
};
await GcfCommon.process(payload, handler);Publish a response to Pub/Sub
Set the topic attribute in metadata/attributes. Response attributes are coerced to strings; common fields request_id, consumer_id, app_id, env are propagated if present.
import { GcfCommon } from 'gcf-common-lib';
const payload = {
event: { '@type': 'type.googleapis.com/google.pubsub.v1.PubsubMessage', json: {}, attributes: { topic: 'projects/my-proj/topics/my-topic', request_id: 'r1' } },
context: undefined,
};
await GcfCommon.process(payload, async () => ({ result: 42 }));
// GcfCommon.response() will publish to the provided topicPublish a response to AMQP (RabbitMQ)
Provide either exchange (with optional queue as routing key) or a queue.
import { GcfCommon } from 'gcf-common-lib';
GcfCommon.amqpOptions.url = 'amqp://guest:guest@localhost:5672';
const payload = {
event: { '@type': 'type.googleapis.com/google.pubsub.v1.PubsubMessage', json: {}, attributes: { exchange: 'events', queue: 'route.key', request_id: 'r1' } },
context: undefined,
};
await GcfCommon.process(payload, async () => ({ result: 42 }));API overview
GcfCommon
process<TResponse, E = TEvent>(payload: TPayload<E>, handler: (p: TPayload<E>) => Promise<any> | any): Promise<any>- Runs handler, then calls
response(...)with handler result; on error publishes a structured error viabuildResponse(error)and rethrows.
- Runs handler, then calls
response<E = TEvent>(payload: TPayload<E>, json?: TResponse, attributes?: Dict<any>): Promise<void>- Publishes to Pub/Sub if
topicis present; to AMQP ifexchangeorqueueis present. Attributes are stringified.
- Publishes to Pub/Sub if
buildResponse(error: Error): TResponsegetOptions(payload: TPayload): Promise<Dict<any>>- Parses JSON from
optionsattribute withsafeJsonParseand{}fallback.
- Parses JSON from
getMetadataOrAttribute<E = TEvent>(payload: TPayload<E>): TMetadataOrAttributes- Extracts attributes from GCS finalize, Pub/Sub publish events, or HTTP request body shape.
getRequestMessage(request: express.Request)
Utils
ms({ w?, d?, h?, m?, s? }): numbersec({ w?, d?, h?, m?, s? }): numberindexToA1(idx: number): stringA1ToIndex(value: string): numbercolNumToA1(columnNumber: number): stringA1ToColNum(value: string): numbersafeJsonParse<T>(value: string, fallback?: T): T | undefineddelay(seconds: number): Promise<void>timeoutAfter(seconds?: number): Promise<void>
AmqpHelper
withAmqpConn(fn, url)— acquire AMQP connection (Bluebird disposer) and runfn.withAmqpCh(fn, url, useConfirmChannel = false, prefetch = 1)— channel lifecycle helper.publishAmqp(ch, exchange | undefined, routingKey, json, options?)sendToQueueConfAmqp(ch: ConfirmChannel, queue, json, options?)
MongoHelper
collectionExists(client, name)collectionSafeGet(client, name, options?, afterCreate?)withMongoClient(fn, url, options?)— maintains a shared client in-process.
Testing
- Uses Node’s built-in test runner (
node:test). - Prefer JS tests under
test/*.test.jsfor zero-transpilation. - Avoid network I/O in unit tests by omitting
topic,exchange, andqueueattributes or by stubbingGcfCommon.response.
License
MIT. See LICENSE.
