From 9e9dd8d9358ad0b433681137ef017c46037b652f Mon Sep 17 00:00:00 2001 From: Phil Kunz Date: Thu, 18 Jul 2019 14:25:10 +0200 Subject: [PATCH] fix(core): update --- package-lock.json | 17 ++++--- package.json | 2 +- test/test.ts | 29 +++++++++--- ts/cloudflare.classes.account.ts | 64 +++++++++++++++++--------- ts/cloudflare.classes.worker.ts | 26 +++++++++++ ts/cloudflare.classes.workermanager.ts | 23 ++++++++- ts/cloudflare.classes.zonemanager.ts | 2 +- tslint.json | 1 + 8 files changed, 123 insertions(+), 41 deletions(-) create mode 100644 ts/cloudflare.classes.worker.ts diff --git a/package-lock.json b/package-lock.json index a15ce1c..025e51a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -49,15 +49,14 @@ } }, "@gitzone/tsrun": { - "version": "1.2.6", - "resolved": "https://verdaccio.lossless.one/@gitzone%2ftsrun/-/tsrun-1.2.6.tgz", - "integrity": "sha512-MTgQ7OiKfMpRQRumJp8aGuLCNNyWGjZSxsF+GfZ7cmg2DUtJRyCL0Ybkai1sPdMWG/zE8RUo50WvBKEChdVyvA==", + "version": "1.2.8", + "resolved": "https://verdaccio.lossless.one/@gitzone%2ftsrun/-/tsrun-1.2.8.tgz", + "integrity": "sha512-G65DNcjegxF6w/O9MYD2mlHh+QVUiLuZvgLD5eamOOuWLhzuiE1tDzv5praJ/woJQzzZinDs+IyRyZ5rWKp/fQ==", "dev": true, "requires": { - "@gitzone/tsbuild": "^2.1.8", - "@pushrocks/smartfile": "^7.0.2", - "ts-node": "^8.0.3", - "typescript": "^3.4.2" + "@pushrocks/smartfile": "^7.0.4", + "ts-node": "^8.3.0", + "typescript": "^3.5.3" } }, "@gitzone/tstest": { @@ -568,7 +567,7 @@ }, "buffer-from": { "version": "1.1.1", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "resolved": "https://verdaccio.lossless.one/buffer-from/-/buffer-from-1.1.1.tgz", "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", "dev": true }, @@ -1527,7 +1526,7 @@ }, "source-map": { "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "resolved": "https://verdaccio.lossless.one/source-map/-/source-map-0.6.1.tgz", "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true }, diff --git a/package.json b/package.json index f801f2b..90fea72 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,7 @@ }, "devDependencies": { "@gitzone/tsbuild": "^2.1.11", - "@gitzone/tsrun": "^1.2.6", + "@gitzone/tsrun": "^1.2.8", "@gitzone/tstest": "^1.0.24", "@pushrocks/qenv": "^4.0.0", "@pushrocks/tapbundle": "^3.0.11", diff --git a/test/test.ts b/test/test.ts index 95887fb..d9d86ea 100644 --- a/test/test.ts +++ b/test/test.ts @@ -1,15 +1,23 @@ +// tslint:disable-next-line: no-implicit-dependencies import { expect, tap } from '@pushrocks/tapbundle'; -import cloudflare = require('../ts/index'); +// tslint:disable-next-line: no-implicit-dependencies import { Qenv } from '@pushrocks/qenv'; + +import cloudflare = require('../ts/index'); + const testQenv = new Qenv(process.cwd(), process.cwd() + '/.nogit'); -const testCloudflareAccount = new cloudflare.CloudflareAccount(); -testCloudflareAccount.auth({ - email: testQenv.getEnvVarOnDemand('CF_EMAIL'), - key: testQenv.getEnvVarOnDemand('CF_KEY') +const randomPrefix = Math.floor(Math.random() * 2000); +let testCloudflareAccount: cloudflare.CloudflareAccount; + +tap.test('should create a valid instance of CloudflareAccount', async () => { + testCloudflareAccount = new cloudflare.CloudflareAccount({ + email: testQenv.getEnvVarOnDemand('CF_EMAIL'), + key: testQenv.getEnvVarOnDemand('CF_KEY') + }); }); -const randomPrefix = Math.floor(Math.random() * 2000); + tap.skip.test('.listZones() -> should display an entire account', async tools => { tools.timeout(600000); @@ -60,4 +68,13 @@ tap.test('.purge(some.domain) -> should purge everything', async () => { await testCloudflareAccount.purgeZone('bleu.de'); }); +// WORKERS +tap.test('should create a worker', async () => { + await testCloudflareAccount.workerManager.createWorker('myawesomescript', `addEventListener('fetch', event => { event.respondWith(fetch(event.request)) })`); +}); + +tap.test('should get workers', async () => { + await testCloudflareAccount.workerManager.listWorkers(); +}); + tap.start(); diff --git a/ts/cloudflare.classes.account.ts b/ts/cloudflare.classes.account.ts index 26f60a2..595b8d1 100644 --- a/ts/cloudflare.classes.account.ts +++ b/ts/cloudflare.classes.account.ts @@ -9,19 +9,28 @@ import { ZoneManager } from './cloudflare.classes.zonemanager'; export class CloudflareAccount { private authEmail: string; private authKey: string; + private accountIdentifier: string; public workerManager = new WorkerManager(this); public zoneManager = new ZoneManager(this); - constructor() { - // Nothing here - } - - public auth(optionsArg: { email: string; key: string }) { + /** + * constructor sets auth information on the CloudflareAccountInstance + * @param optionsArg + */ + constructor(optionsArg: { email: string; key: string }) { this.authEmail = optionsArg.email; this.authKey = optionsArg.key; } + public async getAccountIdentifier() { + const route = `/accounts?page=1&per_page=20&direction=desc`; + const response: any = await this.request('GET', route); + this.accountIdentifier = response.result[0].id; + console.log('Account identifier is: ' + this.accountIdentifier); + return this.accountIdentifier; + } + /** * gets a zone id of a domain from cloudflare * @param domainName @@ -80,24 +89,30 @@ export class CloudflareAccount { return response; } - public removeRecord(domainNameArg: string, typeArg: TDnsRecord) { - const done = plugins.smartpromise.defer(); + /** + * removes a record from Cloudflare + * @param domainNameArg + * @param typeArg + */ + public async removeRecord(domainNameArg: string, typeArg: TDnsRecord): Promise { const domain = new plugins.smartstring.Domain(domainNameArg); - this.getRecord(domain.fullName, typeArg).then(responseArg => { - if (responseArg) { - const requestRoute: string = - '/zones/' + responseArg.zone_id + '/dns_records/' + responseArg.id; - this.request('DELETE', requestRoute).then(responseArg => { - done.resolve(responseArg); - }); - } else { - done.reject(); - } - }); - return done.promise; + const cflareRecord = await this.getRecord(domain.fullName, typeArg); + if (cflareRecord) { + const requestRoute: string = `/zones/${cflareRecord.zone_id}/dns_records/${cflareRecord.id}`; + return await this.request('DELETE', requestRoute); + } else { + throw new Error(`could not remove record for ${domainNameArg} with type ${typeArg}`); + } } + /** + * updates a record + * @param domainNameArg + * @param typeArg + * @param valueArg + */ public updateRecord(domainNameArg: string, typeArg: string, valueArg) { + // TODO: implement const done = plugins.smartpromise.defer(); const domain = new plugins.smartstring.Domain(domainNameArg); return done.promise; @@ -146,7 +161,7 @@ export class CloudflareAccount { const respone = await this.request('DELETE', requestUrl, payload); } - public request(methodArg: string, routeArg: string, dataArg = {}) { + public request(methodArg: string, routeArg: string, dataArg: any = {}, requestHeadersArg = {}): Promise { const done = plugins.smartpromise.defer(); const options: plugins.smartrequest.ISmartRequestOptions = { method: methodArg, @@ -154,11 +169,14 @@ export class CloudflareAccount { 'Content-Type': 'application/json', 'X-Auth-Email': this.authEmail, 'X-Auth-Key': this.authKey, - 'Content-Length': Buffer.byteLength(JSON.stringify(dataArg)) + 'Content-Length': Buffer.byteLength(JSON.stringify(dataArg)), + ...requestHeadersArg }, - requestBody: dataArg + requestBody: dataArg, }; + // console.log(options); + let retryCount = 0; // count the amount of retries const makeRequest = async () => { @@ -173,7 +191,7 @@ export class CloudflareAccount { retryRequest(); } else if (response.statusCode === 400) { console.log(`bad request for route ${routeArg}! Going to retry!`); - retryRequest(); + console.log(response.body); } else { console.log(response.statusCode); done.reject(new Error('request failed')); diff --git a/ts/cloudflare.classes.worker.ts b/ts/cloudflare.classes.worker.ts new file mode 100644 index 0000000..49b87c8 --- /dev/null +++ b/ts/cloudflare.classes.worker.ts @@ -0,0 +1,26 @@ +import { WorkerManager } from './cloudflare.classes.workermanager'; + +export class Worker { + // STATIC + public static async fromApiObject(workerManager: WorkerManager, apiObject): Promise { + console.log(apiObject); + return new Worker(workerManager); + } + + // INSTANCE + private workerManager: WorkerManager; + + public id: string; + public etag: string; + public createdOn: string; + public modifiedOn: string; + + public routes: string[] = []; + constructor(workerManagerArg: WorkerManager) { + this.workerManager = workerManagerArg; + } + + public setRoutes(routeArray: string[]) { + + } +} diff --git a/ts/cloudflare.classes.workermanager.ts b/ts/cloudflare.classes.workermanager.ts index d456cab..14fd1f8 100644 --- a/ts/cloudflare.classes.workermanager.ts +++ b/ts/cloudflare.classes.workermanager.ts @@ -1,10 +1,31 @@ import * as plugins from './cloudflare.plugins'; import { CloudflareAccount } from './cloudflare.classes.account'; +import { Worker } from './cloudflare.classes.worker'; export class WorkerManager { - public cfAccount: CloudflareAccount; + private cfAccount: CloudflareAccount; constructor(cfAccountArg: CloudflareAccount) { this.cfAccount = cfAccountArg; } + + public async createWorker(workerName: string, workerScript: string): Promise { + const accountIdentifier = await this.cfAccount.getAccountIdentifier(); + const route = `/accounts/${accountIdentifier}/workers/scripts/${workerName}`; + const responseBody = await this.cfAccount.request('PUT', route, workerScript, { + 'Content-Type': 'application/javascript', + 'Content-Length': Buffer.byteLength(workerScript) + }); + return Worker.fromApiObject(this, responseBody); + } + + /** + * lists workers + */ + public async listWorkers() { + const accountIdentifier = await this.cfAccount.getAccountIdentifier(); + const route = `/accounts/${accountIdentifier}/workers/scripts`; + const response = await this.cfAccount.request('GET', route); + console.log(response); + } } diff --git a/ts/cloudflare.classes.zonemanager.ts b/ts/cloudflare.classes.zonemanager.ts index e95d623..7e70d65 100644 --- a/ts/cloudflare.classes.zonemanager.ts +++ b/ts/cloudflare.classes.zonemanager.ts @@ -2,7 +2,7 @@ import * as plugins from './cloudflare.plugins'; import { CloudflareAccount } from './cloudflare.classes.account'; export class ZoneManager { - public cfAccount: CloudflareAccount; + private cfAccount: CloudflareAccount; public zoneName: string; constructor(cfAccountArg: CloudflareAccount) { diff --git a/tslint.json b/tslint.json index d4ea2e9..2a46c44 100644 --- a/tslint.json +++ b/tslint.json @@ -3,6 +3,7 @@ "rules": { "semicolon": [true, "always"], "no-console": false, + "no-return-await": false, "ordered-imports": false, "object-literal-sort-keys": false, "member-ordering": {