@saleandwin/common
v1.0.5
Published
Common utilities for framework-ts projects
Downloads
9
Maintainers
Readme
@saleandwin/common
Common utilities for framework-ts projects, providing database transaction management, API response formatting, pagination, and batch validation functionality.
Installation
pnpm add @saleandwin/commonFeatures
- TransactionBuilder: A powerful utility for building and executing batch database operations with Cloudflare D1
- API Response Utilities: Standardized API response formatting for Next.js applications
- Pagination Tools: Complete pagination parameter validation and response formatting
- Batch Validator: Advanced validation framework for complex database operations
- Cloudflare API Client: Complete Cloudflare API client with support for Zones, DNS, Pages, and Workers
- Type-safe database operations
- Built for Cloudflare Workers and Next.js environment
Usage
TransactionBuilder
The TransactionBuilder class helps you build and execute batch database operations atomically.
import { createTransaction, TransactionBuilder } from '@saleandwin/common';
// Using the factory function
const transaction = await createTransaction();
// Or create directly
const db = await getYourDatabase();
const transaction = new TransactionBuilder(db);
// Add statements to the transaction
transaction
.add(db.prepare('INSERT INTO users (name) VALUES (?)').bind('John'))
.add(db.prepare('INSERT INTO users (name) VALUES (?)').bind('Jane'))
.addAll([
db.prepare('UPDATE users SET active = ? WHERE id = ?').bind(true, 1),
db.prepare('UPDATE users SET active = ? WHERE id = ?').bind(true, 2)
]);
// Execute all statements atomically
const results = await transaction.execute();
// Clear statements for reuse
transaction.clear();API Response Utilities
Standardized API response formatting for Next.js applications.
import {
createSuccessResponse,
createErrorResponse,
createAuthErrorResponse,
validatePaginationParamsFromURL
} from '@saleandwin/common';
// Success response
return createSuccessResponse({ users: [] }, '获取成功');
// Error response
return createErrorResponse('用户不存在', 404);
// Auth error
return createAuthErrorResponse('请先登录');Pagination Tools
Complete pagination parameter validation and response formatting.
import {
validatePaginationParamsFromURL,
calculatePaginationResult,
createStandardResponse,
PAGINATION_CONSTRAINTS
} from '@saleandwin/common';
// Validate pagination from URL
const { isValid, params, error } = validatePaginationParamsFromURL(searchParams);
if (!isValid) {
return createErrorResponse(error);
}
// Calculate pagination result
const pagination = calculatePaginationResult(params.page, params.limit, totalCount);
// Create standardized response
return createStandardResponse('users', userData, pagination);Batch Validator
Advanced validation framework for complex database operations.
import {
BatchValidator,
createBatchValidator,
notExists,
exists,
validateUserStatus
} from '@saleandwin/common';
const validator = createBatchValidator();
const validationResult = await validator.validate([
{
name: 'checkUserExists',
statement: db.prepare('SELECT * FROM users WHERE email = ?').bind(email),
validator: notExists('用户已存在')
},
{
name: 'checkInviteCode',
statement: db.prepare('SELECT * FROM invite_codes WHERE code = ?').bind(code),
validator: validateInviteCode()
}
]);
if (!validationResult.valid) {
return createErrorResponse(validationResult.error);
}Cloudflare API Client
Complete Cloudflare API client with support for Zones, DNS, Pages, and Workers management.
import { CloudflareApiClient } from '@saleandwin/common';
// Initialize client
const client = new CloudflareApiClient({
apiToken: 'your-api-token',
accountId: 'your-account-id'
});
// Zone management
const zones = await client.getZones();
const newZone = await client.createZone({
name: 'example.com',
jump_start: true
});
// DNS management
const dnsRecords = await client.getDnsRecords(zoneId);
const newRecord = await client.createDnsRecord(zoneId, {
type: 'A',
name: 'www',
content: '192.168.1.1',
proxied: true
});
// Pages management
const projects = await client.getPagesProjects();
const newProject = await client.createPagesProject({
name: 'my-site',
production_branch: 'main'
});
// Worker management
const workers = await client.getWorkerScripts();
await client.createWorkerScript('my-worker', {
script: 'export default { fetch() { return new Response("Hello!"); } }'
});
// Utility methods
const isConnected = await client.checkConnection();
const accountId = await client.getAccountId();API Reference
TransactionBuilder
Static Methods
createInstance(): Promise<TransactionBuilder>- Creates a new instance with automatic database connection
Instance Methods
add(statement: D1PreparedStatement): this- Add a single statement to the transactionaddAll(statements: D1PreparedStatement[]): this- Add multiple statements to the transactionexecute(): Promise<D1Result[]>- Execute all statements atomicallyclear(): this- Clear all statements from the transactioncount(): number- Get the number of statements in the transaction
Factory Function
createTransaction(): Promise<TransactionBuilder>- Convenience function to create a new TransactionBuilder instance
Requirements
- Node.js >= 18.0.0
- Cloudflare Workers environment
@opennextjs/cloudflarepeer dependency
Development
# Install dependencies
pnpm install
# Build the package
pnpm run build
# Run tests
pnpm test
# Watch mode for development
pnpm run devLicense
MIT
