Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,44 @@ Converts between Azure Functions HTTP triggers and Next.js InternalEvent/Interna
**Build Process:**
Uses OpenNext's AWS build with Azure-specific overrides, then adds Azure Functions metadata (`host.json`, `function.json`) for v3 programming model.

## Database & Service Bindings

Type-safe bindings for Azure services. Configure once in `azure.config.json`, access everywhere with full type safety.

```json
{
"bindings": {
"DB": {
"type": "cosmos-sql",
"databaseName": "mydb",
"throughput": 400
},
"CACHE": {
"type": "redis",
"sku": "Basic",
"capacity": 0
}
}
}
```

```typescript
// app/api/users/route.ts
import { getBinding } from "opennextjs-azure/bindings";

export async function GET() {
const db = getBinding<"cosmos-sql">("DB");

const database = db.database("mydb");
const container = database.container("users");
const { resources } = await container.items.readAll().fetchAll();

return Response.json(resources);
}
```

Infrastructure provisioned automatically. Supports: Cosmos DB, Postgres, MySQL, Redis, Service Bus, Event Hub.

## CLI Commands

### `init --scaffold` (Recommended for new projects)
Expand Down
8 changes: 8 additions & 0 deletions build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export default defineBuildConfig({
"src/index",
"src/cli/index",
"src/config/index",
"src/bindings/index",
"src/infrastructure/bindings",
"src/overrides/incrementalCache/azure-blob",
"src/overrides/tagCache/azure-table",
"src/overrides/queue/azure-queue",
Expand Down Expand Up @@ -45,6 +47,12 @@ export default defineBuildConfig({
"@azure/data-tables",
"@azure/storage-queue",
"@azure/functions",
"@azure/cosmos",
"@azure/service-bus",
"@azure/event-hubs",
"commander",
"redis",
"pg",
"mysql2",
],
});
33 changes: 32 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
"import": "./dist/config/index.js",
"types": "./dist/config/index.d.ts"
},
"./bindings": {
"import": "./dist/bindings/index.js",
"types": "./dist/bindings/index.d.ts"
},
"./adapters/wrappers/azure-functions.js": {
"import": "./dist/adapters/wrappers/azure-functions.js",
"types": "./dist/adapters/wrappers/azure-functions.d.ts"
Expand Down Expand Up @@ -78,20 +82,47 @@
"commander": "^11.1.0"
},
"devDependencies": {
"@azure/cosmos": "^4.0.0",
"@azure/event-hubs": "^5.11.0",
"@azure/service-bus": "^7.9.0",
"@types/node": "^20.11.0",
"@types/pg": "^8.11.0",
"@typescript-eslint/eslint-plugin": "^6.20.0",
"@typescript-eslint/parser": "^6.20.0",
"eslint": "^8.56.0",
"rimraf": "^5.0.5",
"mysql2": "^3.9.0",
"pg": "^8.11.0",
"prettier": "^3.5.3",
"prettier-plugin-tailwindcss": "^0.5.0",
"redis": "^4.6.0",
"rimraf": "^5.0.5",
"typescript": "^5.3.3",
"unbuild": "^2.0.0",
"vitest": "^1.2.0"
},
"peerDependencies": {
"next": ">=13.4.0"
},
"peerDependenciesMeta": {
"@azure/cosmos": {
"optional": true
},
"@azure/service-bus": {
"optional": true
},
"@azure/event-hubs": {
"optional": true
},
"redis": {
"optional": true
},
"pg": {
"optional": true
},
"mysql2": {
"optional": true
}
},
"engines": {
"node": ">=18.0.0"
}
Expand Down
197 changes: 197 additions & 0 deletions src/bindings/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
import type { CosmosClient } from "@azure/cosmos";
import type { Pool as PostgresPool } from "pg";
import type { RedisClientType } from "redis";
import type { ServiceBusClient } from "@azure/service-bus";
import type { EventHubProducerClient } from "@azure/event-hubs";
import type { BindingType } from "../types/index.js";

export type BindingClientMap = {
"cosmos-sql": CosmosClient;
"cosmos-nosql": CosmosClient;
"postgres-flexible": PostgresPool;
"mysql-flexible": PostgresPool;
redis: RedisClientType;
"service-bus-queue": ServiceBusClient;
"service-bus-topic": ServiceBusClient;
"event-hub": EventHubProducerClient;
};

interface BindingMetadata {
type: BindingType;
envVars: {
connectionString?: string;
endpoint?: string;
host?: string;
primaryKey?: string;
};
}

interface BindingFactory {
create(envVars: BindingMetadata["envVars"]): unknown;
shouldCache: boolean;
}

const BINDING_FACTORIES: Record<BindingType, BindingFactory> = {
"cosmos-sql": {
create: envVars => {
const { CosmosClient } = require("@azure/cosmos");
return new CosmosClient(process.env[envVars.endpoint!]!, {
key: process.env[envVars.primaryKey!],
});
},
shouldCache: true,
},

"cosmos-nosql": {
create: envVars => {
const { CosmosClient } = require("@azure/cosmos");
return new CosmosClient(process.env[envVars.connectionString!]!);
},
shouldCache: true,
},

"postgres-flexible": {
create: envVars => {
const { Pool } = require("pg");
return new Pool({
connectionString: process.env[envVars.connectionString!],
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
},
shouldCache: true,
},

"mysql-flexible": {
create: envVars => {
const mysql = require("mysql2/promise");
return mysql.createPool({
uri: process.env[envVars.connectionString!],
waitForConnections: true,
connectionLimit: 10,
});
},
shouldCache: true,
},

redis: {
create: envVars => {
const { createClient } = require("redis");
return createClient({
url: process.env[envVars.connectionString!],
socket: {
connectTimeout: 5000,
reconnectStrategy: (retries: number) => Math.min(retries * 50, 500),
},
});
},
shouldCache: true,
},

"service-bus-queue": {
create: envVars => {
const { ServiceBusClient } = require("@azure/service-bus");
return new ServiceBusClient(process.env[envVars.connectionString!]!);
},
shouldCache: true,
},

"service-bus-topic": {
create: envVars => {
const { ServiceBusClient } = require("@azure/service-bus");
return new ServiceBusClient(process.env[envVars.connectionString!]!);
},
shouldCache: true,
},

"event-hub": {
create: envVars => {
const { EventHubProducerClient } = require("@azure/event-hubs");
return new EventHubProducerClient(process.env[envVars.connectionString!]!);
},
shouldCache: true,
},
};

let bindingsMetadata: Record<string, BindingMetadata> | null = null;
const clientCache = new Map<string, unknown>();

function loadBindingsMetadata(): Record<string, BindingMetadata> {
if (bindingsMetadata) {
return bindingsMetadata;
}

try {
const metadataPath = process.env.BINDINGS_METADATA_PATH || "./.bindings.json";
bindingsMetadata = require(metadataPath);
return bindingsMetadata!;
} catch {
return {};
}
}

/**
* Get a typed binding client by name.
*
* @example
* ```ts
* const db = getBinding<'cosmos-sql'>('DATABASE');
* const cache = getBinding<'redis'>('CACHE');
* const pg = getBinding<'postgres-flexible'>('POSTGRES');
* ```
*/
export function getBinding<T extends BindingType>(name: string): BindingClientMap[T] {
if (clientCache.has(name)) {
return clientCache.get(name) as BindingClientMap[T];
}

const metadata = loadBindingsMetadata();

if (!metadata[name]) {
const available = Object.keys(metadata);
throw new Error(
`Binding "${name}" not found.\n` +
(available.length > 0
? `Available bindings: ${available.join(", ")}`
: `No bindings configured in azure.config.json`) +
`\n\nAdd to azure.config.json:\n` +
`{\n "bindings": {\n "${name}": { "type": "..." }\n }\n}`
);
}

const binding = metadata[name];
const factory = BINDING_FACTORIES[binding.type];

if (!factory) {
throw new Error(
`Unknown binding type "${binding.type}" for binding "${name}".\n` +
`Supported types: ${Object.keys(BINDING_FACTORIES).join(", ")}`
);
}

for (const [, envVarName] of Object.entries(binding.envVars)) {
if (envVarName && !process.env[envVarName]) {
throw new Error(
`Missing environment variable "${envVarName}" for binding "${name}".\n` +
`This should have been set during deployment. Try redeploying.`
);
}
}

const client = factory.create(binding.envVars);

if (factory.shouldCache) {
clientCache.set(name, client);
}

return client as BindingClientMap[T];
}

/**
* Clear the binding client cache.
* Useful for testing or when you need to recreate connections.
*/
export function clearBindingsCache(): void {
clientCache.clear();
}
Loading