@cardql/node
v1.0.1
Published
CardQL SDK for Node.js and serverless applications
Downloads
13
Maintainers
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/nodeQuick Start
Environment Variables
Set up your environment variables:
CARDQL_API_KEY=your-api-key
CARDQL_ENDPOINT=https://your-cardql-endpoint.com/graphqlBasic 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 resultsHealth 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.
