Skip to content

Commit

Permalink
clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
aflanagan committed May 7, 2024
1 parent 57d93cf commit 10c02d0
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 51 deletions.
36 changes: 15 additions & 21 deletions lib/cronitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,13 @@ function Cronitor(apiKey, config = {}) {
const path = config.config || process.env.CRONITOR_CONFIG;
const version = config.apiVersion || process.env.CRONITOR_API_VERSION || null;
const timeout = config.timeout || process.env.CRONITOR_TIMEOUT || 10000;
const env = config.env || process.env.CRONITOR_ENV || 'production';
const env = config.env || process.env.CRONITOR_ENV || null;
const headers = {
'User-Agent': 'cronitor-js',
'Authorization': 'Basic ' + new Buffer.from(apiKey + ':').toString('base64'),
};

if (path) {
this.config = this.readConfig({ path });
this.path = path;
}

if (path) this.path = path;
if (version) headers['Cronitor-Version'] = version;

this._api = {
Expand All @@ -49,42 +45,40 @@ function Cronitor(apiKey, config = {}) {
this.Monitor._api = this._api;
this.Event._api = this._api;

this.generateConfig = async ({path=null, group=null}={}) => {
this.generateConfig = async ({path=this.path, group=null}={}) => {
let url = 'https://cronitor.io/api/monitors.yaml';

if (!this.path && !path) {
throw new Errors.ConfigError('Must initialize Cronitor with a "config" keyword arg as a valid file path or pass `path` as a keyword arg to generateConfig.');
} else if (!path) {
path = this.path;

if (!path) {
throw new Errors.ConfigError('Must initialize Cronitor with a "config" keyword arg as a valid file path or pass `path` as a keyword arg to generateConfig.');
}

if (group) { url += `?group=${group}` }
if (group) url += `?group=${group}`;

try {
// Make HTTP GET request to fetch the YAML file
const response = await this._api.axios.get(url, { responseType: 'blob' });
await fs.writeFile(path, response.data, 'utf8');
const response = await this._api.axios.get(url, { responseType: 'blob' });
await fs.writeFile(path, response.data, 'utf8');
return true
} catch (error) {
console.error('Failed to download or save the YAML file:', error);
return false
}
};


this.applyConfig = async function({ path = this.path, rollback = false } = {}) {
if (!path) throw new Errors.ConfigError('Must include a path to config file e.g. cronitor.applyConfig({path: \'./cronitor.yaml\'})');

try {
config = await this.readConfig({ path, output: true});
} catch (err) {
} catch (err) {
console.error('Error reading config:', err);
return false
}

try {
await Monitor.put(config, {rollback, format: Monitor.requestType.YAML});
console.log(`Cronitor config ${rollback ? 'validated' : 'applied'} successfully.`)
console.log(`Cronitor config ${rollback ? 'validated' : 'applied'} successfully.`)
return true
} catch (err) {
console.error(`Error applying config: ${err}`);
Expand All @@ -97,7 +91,7 @@ function Cronitor(apiKey, config = {}) {
};

this.readConfig = async function({path = null, output = false}={}) {
if (!path) throw new Errors.ConfigError('Must include a path to config file e.g. cronitor.readConfig({path: \'./cronitor.yaml\'})');
if (!path) throw new Errors.ConfigError('Must include a path to config file e.g. cronitor.readConfig({path: \'./cronitor.yaml\'})');
if (!this.path) this.path = path;

try {
Expand All @@ -111,7 +105,7 @@ function Cronitor(apiKey, config = {}) {
}
};


this.wrap = function(key, callback) {
const _cronitor = this;
return async function(args) {
Expand Down
30 changes: 15 additions & 15 deletions lib/monitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,39 +19,39 @@ class Monitor {
};
}

static async put(data, {rollback = false, format = Monitor.requestType.JSON} = {}) {
if (format === Monitor.requestType.YAML) {
static async put(data, {rollback = false, format = Monitor.requestType.JSON} = {}) {

if (format === Monitor.requestType.YAML) {
return this.putYaml(yaml.dump({...data, rollback}))
}

}

// if a user passed a single monitor object, wrap it in an array
if (!Array.isArray(data)) {
data = [data];
}
try {

try {
const resp = await this._api.axios.put(this._api.monitorUrl(), {monitors: data, rollback});
const monitors = resp.data.monitors.map((_m) => {
const m = new Monitor(_m.key);
m.data = _m;
return m;
});
return monitors.length > 1 ? monitors : monitors[0];
} catch (err) {
return monitors.length > 1 ? monitors : monitors[0];
} catch (err) {
throw new Errors.MonitorNotCreated(err.message);
}
}

static async putYaml(payload) {
try {
try {
const resp = await this._api.axios.put(
this._api.monitorUrl(),
payload,
this._api.monitorUrl(),
payload,
{ headers: {'Content-Type': 'application/yaml'} }
);
return yaml.load(resp.data);
);
return yaml.load(resp.data);
} catch (err) {
throw new Errors.MonitorNotCreated(err.message);
}
Expand Down
30 changes: 15 additions & 15 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const Monitor = require('../lib/monitor'),
sinonChai = require('sinon-chai'),
sinonStubPromise = require('sinon-stub-promise'),
fs = require('fs').promises,
yaml = require('js-yaml'),
yaml = require('js-yaml'),
expect = chai.expect;


Expand All @@ -30,7 +30,7 @@ describe('Config Parser', () => {
await cronitor.readConfig({path: './test/cronitor.yaml'});
expect(cronitor.config).to.not.be.undefined;
});

});

context('validateConfig', () => {
Expand All @@ -56,7 +56,7 @@ describe('Config Parser', () => {

context('applyConfig', () => {
afterEach(async () => {
sinon.restore();
sinon.restore();
cronitor.path = null;
});

Expand All @@ -79,37 +79,37 @@ describe('Config Parser', () => {

context('generateConfig', () => {
afterEach(async () => {
sinon.restore();
await fs.unlink('./cronitor-test.yaml');
sinon.restore();
await fs.unlink('./cronitor-test.yaml');
});

it('should write a YAML file to the location specified', async () => {
const stub = sinon.stub(cronitor._api.axios, 'get');
const dummyData = await fs.readFile('./test/cronitor.yaml', 'utf8');
stub.resolves({data: dummyData})
const resp = await cronitor.generateConfig({path: './cronitor-test.yaml'});

expect(stub).to.be.called;
expect(resp).to.be.true;

// read the config file and check that it is valid YAML
try {
const data = await fs.readFile('./cronitor-test.yaml', 'utf8');
const config = yaml.load(data);
expect(Object.keys(config)).to.include('jobs');
expect(Object.keys(config)).to.include('checks');
expect(Object.keys(config)).to.include('heartbeats');
expect(Object.keys(config)).to.include('heartbeats');
} catch (err) {
console.error('Failed to read the file:', err);
}
}
});

it('should allow a group to be specified', async () => {
it('should allow a group to be specified', async () => {
const stub = sinon.stub(cronitor._api.axios, 'get');
const dummyData = await fs.readFile('./test/cronitor.yaml', 'utf8');
stub.resolves({data: dummyData})
const resp = await cronitor.generateConfig({path: './cronitor-test.yaml', group: 'test-group'});

expect(stub).to.be.calledWith('https://cronitor.io/api/monitors.yaml?group=test-group');
expect(resp).to.be.true;
});
Expand Down Expand Up @@ -326,20 +326,20 @@ describe.skip('test wrap cron', () => {

describe.skip('functional test YAML API', () => {
const cronitor = require('../lib/cronitor')('ADD_YOUR_API_KEY')
it('should read a config file and validate it', async () => {

it('should read a config file and validate it', async () => {
const validated = await cronitor.validateConfig({path: './test/cronitor.yaml'});
expect(validated).to.be.true;
});

it('should read a config file and apply it', async () => {
it('should read a config file and apply it', async () => {
const applied = await cronitor.applyConfig({path: './test/cronitor.yaml'});
expect(applied).to.be.true;

// clean up if this runs against prod
const config = await cronitor.readConfig({path: './test/cronitor.yaml', output: true});
keys = Object.keys(config).map((k) => Object.keys(config[k])).flat();
keys.map(async (k) => {
keys.map(async (k) => {
const monitor = new cronitor.Monitor(k);
await monitor.delete()
});
Expand Down

0 comments on commit 10c02d0

Please sign in to comment.