npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@cardql/node

v1.0.1

Published

CardQL SDK for Node.js and serverless applications

Downloads

13

Readme

@cardql/node

CardQL SDK for Node.js and serverless applications with enhanced server-side features.

Installation

npm install @cardql/node
# or
yarn add @cardql/node
# or
pnpm add @cardql/node

Quick Start

Environment Variables

Set up your environment variables:

CARDQL_API_KEY=your-api-key
CARDQL_ENDPOINT=https://your-cardql-endpoint.com/graphql

Basic Usage

import { CardQL } from "@cardql/node";

// Automatically uses environment variables
const cardql = new CardQL();

// Or provide configuration explicitly
const cardql = new CardQL({
  apiKey: "your-api-key",
  endpoint: "https://api.cardql.com/graphql",
  enableLogging: true,
  logLevel: "info",
});

// Use the API
const customer = await cardql.api.createCustomer({
  firstName: "John",
  lastName: "Doe",
  email: "[email protected]",
});

Environment-Specific Configuration

import { CardQL } from "@cardql/node";

// Create client with environment-specific defaults
const cardql = CardQL.forEnvironment("production", {
  apiKey: process.env.CARDQL_API_KEY,
  endpoint: process.env.CARDQL_ENDPOINT,
});

Express.js Integration

Middleware Setup

import express from "express";
import { cardqlMiddleware, cardqlErrorHandler } from "@cardql/node";

const app = express();

// Add CardQL middleware
app.use(
  cardqlMiddleware({
    enableLogging: true,
    logLevel: "info",
  })
);

// Add error handling middleware
app.use(cardqlErrorHandler());

// Use in routes
app.post("/payments", async (req, res) => {
  const payment = await req.cardql!.api.createPayment({
    amount: req.body.amount,
    currency: req.body.currency,
    merchantID: req.body.merchantID,
    userID: req.user.id,
  });

  res.json(payment);
});

Serverless Functions

AWS Lambda

import { withCardQL } from "@cardql/node";

export const handler = withCardQL(async (event, context) => {
  const payment = await context.cardql.api.createPayment({
    amount: event.amount,
    currency: "USD",
    merchantID: event.merchantID,
    userID: event.userID,
  });

  return {
    statusCode: 200,
    body: JSON.stringify(payment),
  };
});

Vercel Functions

import { createCardQLContext } from "@cardql/node";
import type { VercelRequest, VercelResponse } from "@vercel/node";

const { cardql } = createCardQLContext();

export default async function handler(req: VercelRequest, res: VercelResponse) {
  try {
    const payment = await cardql.api.createPayment(req.body);
    res.json(payment);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
}

Netlify Functions

import { CardQL } from "@cardql/node";
import type { Handler } from "@netlify/functions";

const cardql = new CardQL();

export const handler: Handler = async (event, context) => {
  try {
    const body = JSON.parse(event.body || "{}");
    const payment = await cardql.api.createPayment(body);

    return {
      statusCode: 200,
      body: JSON.stringify(payment),
    };
  } catch (error) {
    return {
      statusCode: 500,
      body: JSON.stringify({ error: error.message }),
    };
  }
};

Configuration

Environment Variables

| Variable | Description | Default | | ----------------- | ------------------------------- | -------------------------------- | | CARDQL_API_KEY | Your CardQL API key | Required | | CARDQL_ENDPOINT | GraphQL endpoint URL | https://api.cardql.com/graphql | | CARDQL_TIMEOUT | Request timeout in milliseconds | 30000 | | CARDQL_RETRIES | Number of retry attempts | 3 |

Configuration Options

interface NodeCardQLConfig {
  apiKey?: string;
  endpoint?: string;
  timeout?: number;
  retries?: number;
  enableLogging?: boolean;
  logLevel?: "error" | "warn" | "info" | "debug";
  env?: "development" | "staging" | "production";
}

Environment Presets

// Development - more logging, longer timeouts
const cardql = CardQL.forEnvironment("development");

// Staging - balanced settings
const cardql = CardQL.forEnvironment("staging");

// Production - optimized for performance
const cardql = CardQL.forEnvironment("production");

Logging

The Node.js SDK includes comprehensive logging capabilities:

const cardql = new CardQL({
  enableLogging: true,
  logLevel: "debug",
});

// Enable/disable logging at runtime
cardql.setLogging(true, "info");

// Logs include:
// - GraphQL requests and responses
// - Errors and retries
// - Performance metrics
// - Health check results

Health Checks

// Perform a health check
const isHealthy = await cardql.healthCheck();

if (!isHealthy) {
  console.error("CardQL service is not available");
}

// Get client statistics
const stats = cardql.getStats();
console.log("CardQL Stats:", stats);

Error Handling

The SDK provides structured error handling:

import { CardQLError } from "@cardql/node";

try {
  const payment = await cardql.api.createPayment(input);
} catch (error) {
  if (error instanceof CardQLError) {
    console.error("CardQL Error:", error.code, error.message);

    // Handle specific error types
    switch (error.code) {
      case "VALIDATION_ERROR":
        // Handle validation errors
        break;
      case "INSUFFICIENT_PERMISSIONS":
        // Handle permission errors
        break;
      default:
        // Handle other errors
        break;
    }
  }
}

Performance Optimization

Connection Reuse

// Create a single instance and reuse it
const cardql = new CardQL();

// In Express.js, use middleware to share the instance
app.use(cardqlMiddleware());

Caching (Optional)

// Implement your own caching layer
class CachedCardQL {
  private cache = new Map();

  constructor(private cardql: CardQL) {}

  async getCustomer(id: string) {
    if (this.cache.has(id)) {
      return this.cache.get(id);
    }

    const customer = await this.cardql.api.getCustomer(id);
    this.cache.set(id, customer);
    return customer;
  }
}

Best Practices

1. Environment Configuration

Always use environment variables for sensitive data:

// ✅ Good
const cardql = new CardQL(); // Uses env vars

// ❌ Avoid
const cardql = new CardQL({
  apiKey: "hardcoded-key", // Don't hardcode secrets
});

2. Error Handling

Always handle errors gracefully:

// ✅ Good
try {
  const payment = await cardql.api.createPayment(input);
  return { success: true, payment };
} catch (error) {
  logger.error("Payment creation failed:", error);
  return { success: false, error: error.message };
}

3. Health Checks

Implement health checks in production:

// Add health check endpoint
app.get("/health", async (req, res) => {
  const isCardQLHealthy = await req.cardql!.healthCheck();

  res.status(isCardQLHealthy ? 200 : 503).json({
    status: isCardQLHealthy ? "healthy" : "unhealthy",
    services: {
      cardql: isCardQLHealthy,
    },
  });
});

License

MIT

Support

For support, please contact the CardQL team or visit our documentation.