Go to file
2024-06-15 19:56:32 +02:00
.vscode fix(core): update 2022-09-27 19:24:52 +02:00
test switch to official cloudflare api client while keeping class based approach 2024-06-15 19:47:09 +02:00
ts switch to official cloudflare api client while keeping class based approach 2024-06-15 19:47:09 +02:00
.gitignore fix(core): update 2020-06-10 05:34:47 +00:00
license update license info 2024-06-15 19:56:32 +02:00
npmextra.json update readme 2024-06-15 19:55:48 +02:00
package.json update readme 2024-06-15 19:55:48 +02:00
pnpm-lock.yaml switch to official cloudflare api client while keeping class based approach 2024-06-15 19:47:09 +02:00
qenv.yml fix(core): update 2020-02-19 16:58:46 +00:00
readme.hints.md update readme 2024-06-15 19:55:48 +02:00
readme.md update readme 2024-06-15 19:55:48 +02:00
tsconfig.json update readme 2024-06-15 19:55:48 +02:00

@apiclient.xyz/cloudflare

easy cloudflare management

Install

To install the @apiclient.xyz/cloudflare package, you can use npm. Simply run the following command:

npm install @apiclient.xyz/cloudflare

Make sure to include it in your dependencies in package.json.

Usage

Initial Setup

First, let's start by importing the required modules and setting up an instance of CloudflareAccount with your API token. This instance will be used to interact with the Cloudflare API.

import * as cflare from '@apiclient.xyz/cloudflare';

// Initialize Cloudflare Account
const myCflareAccount = new cflare.CloudflareAccount('mySuperAwesomeAccountToken');

Managing Zones

List All Zones

To list all zones in your Cloudflare account, you can use the listZones method:

const listAllZones = async () => {
  const myZones = await myCflareAccount.convenience.listZones();
  console.log(myZones);
};

Get Zone ID

To get the ID of a specific zone (domain), use the getZoneId method:

const getZoneId = async (domainName: string) => {
  try {
    const zoneId = await myCflareAccount.convenience.getZoneId(domainName);
    console.log(`Zone ID for ${domainName}:`, zoneId);
  } catch (error) {
    console.error('Error getting zone ID:', error);
  }
};

Purge Cache for a Zone

To purge all cache for a specific zone:

const purgeZoneCache = async (domainName: string) => {
  await myCflareAccount.convenience.purgeZone(domainName);
  console.log(`Purged cache for ${domainName}`);
};

Managing DNS Records

List DNS Records

To list all DNS records for a specific zone:

const listDnsRecords = async (domainName: string) => {
  try {
    const records = await myCflareAccount.convenience.listRecords(domainName);
    console.log(`DNS Records for ${domainName}:`, records);
  } catch (error) {
    console.error('Error listing DNS records:', error);
  }
};

Get a Specific Record

To get a specific DNS record by type (e.g., A, AAAA, CNAME, etc.):

const getDnsRecord = async (domainName: string, recordType: string) => {
  try {
    const record = await myCflareAccount.convenience.getRecord(domainName, recordType);
    console.log(`DNS Record (${recordType}) for ${domainName}:`, record);
  } catch (error) {
    console.error('Error getting DNS record:', error);
  }
};

Create a DNS Record

To create a new DNS record:

const createDnsRecord = async (domainName: string, recordType: string, content: string) => {
  try {
    const response = await myCflareAccount.convenience.createRecord(domainName, recordType, content, 120);
    console.log(`Created DNS record (${recordType}) for ${domainName}:`, response);
  } catch (error) {
    console.error('Error creating DNS record:', error);
  }
};

Remove a DNS Record

To remove a DNS record:

const removeDnsRecord = async (domainName: string, recordType: string) => {
  try {
    await myCflareAccount.convenience.removeRecord(domainName, recordType);
    console.log(`Removed DNS record (${recordType}) for ${domainName}`);
  } catch (error) {
    console.error('Error removing DNS record:', error);
  }
};

Clean a DNS Record

To clean (remove) all records of a specific type for a domain:

const cleanDnsRecord = async (domainName: string, recordType: string) => {
  try {
    await myCflareAccount.convenience.cleanRecord(domainName, recordType);
    console.log(`Cleaned DNS records (${recordType}) for ${domainName}`);
  } catch (error) {
    console.error('Error cleaning DNS record:', error);
  }
};

Managing Workers

Create a Worker

To create a new Cloudflare Worker:

const createWorker = async (workerName: string, workerScript: string) => {
  try {
    const worker = await myCflareAccount.workerManager.createWorker(workerName, workerScript);
    console.log(`Created Worker (${workerName}):`, worker);
  } catch (error) {
    console.error('Error creating Worker:', error);
  }
};

List Workers

To list all workers in your Cloudflare account:

const listWorkers = async () => {
  try {
    const workers = await myCflareAccount.workerManager.listWorkers();
    console.log('Workers:', workers);
  } catch (error) {
    console.error('Error listing workers:', error);
  }
};

Set Worker Routes

To set routes for a Cloudflare Worker:

import { CloudflareWorker } from '@apiclient.xyz/cloudflare';

const setWorkerRoutes = async (worker: CloudflareWorker, routes: Array<{ zoneName: string, pattern: string }>) => {
  try {
    await worker.setRoutes(routes);
    console.log('Routes set successfully for Worker:', worker.id);
  } catch (error) {
    console.error('Error setting routes for Worker:', error);
  }
};

Sample Complete Workflow

Below is a sample workflow that includes all the above features:

import * as cflare from '@apiclient.xyz/cloudflare';

const myCflareAccount = new cflare.CloudflareAccount('mySuperAwesomeAccountToken');

const manageCloudflare = async () => {
  try {
    // List all zones
    const myZones = await myCflareAccount.convenience.listZones();
    console.log('Zones:', myZones);

    // Get Zone ID for a specific domain
    const myZoneId = await myCflareAccount.convenience.getZoneId('example.com');
    console.log('Zone ID:', myZoneId);

    // Purge cache for a zone
    await myCflareAccount.convenience.purgeZone('example.com');
    console.log('Cache purged for example.com');

    // List DNS records for a domain
    const myRecords = await myCflareAccount.convenience.listRecords('example.com');
    console.log('DNS Records:', myRecords);

    // Get a specific DNS record
    const myRecord = await myCflareAccount.convenience.getRecord('sub.example.com', 'A');
    console.log('Specific DNS Record:', myRecord);

    // Create a DNS record
    const createResponse = await myCflareAccount.convenience.createRecord('sub.example.com', 'A', '127.0.0.1');
    console.log('Created DNS Record:', createResponse);

    // Clean DNS records
    await myCflareAccount.convenience.cleanRecord('sub.example.com', 'A');
    console.log('Cleaned DNS Records for sub.example.com');

    // Create a Cloudflare Worker
    const myWorker = await myCflareAccount.workerManager.createWorker('myWorker', `addEventListener('fetch', event => { event.respondWith(fetch(event.request)) })`);
    console.log('Created Worker:', myWorker);

    // Set routes for the Worker
    await myWorker.setRoutes([{ zoneName: 'example.com', pattern: 'https://*example.com/*' }]);
    console.log('Routes set for Worker');

    // List all Workers
    const workers = await myCflareAccount.workerManager.listWorkers();
    console.log('Workers:', workers);
  } catch (error) {
    console.error('Error managing Cloudflare:', error);
  }
};

manageCloudflare();

This complete guide covers initialization, managing Cloudflare zones, DNS records, and Cloudflare Workers comprehensively using TypeScript for enhanced type safety and intellisense. Always ensure to keep your API keys secure and avoid hardcoding them directly in your scripts. undefined