Skip to content

Instantly share code, notes, and snippets.

@wmantly
Created July 23, 2024 18:37
Show Gist options
  • Save wmantly/eb2ef357b2b1390d9649df5e4a4041ab to your computer and use it in GitHub Desktop.
Save wmantly/eb2ef357b2b1390d9649df5e4a4041ab to your computer and use it in GitHub Desktop.
'use strict';
const axios = require('axios');
const conf = require('../conf/conf');
class PorkBun{
baseUrl = 'https://api.porkbun.com/api/json/v3';
constructor(apiKey, secretApiKey){
this.apiKey = apiKey;
this.secretApiKey = secretApiKey;
}
async post(url, data){
let res;
try{
data = {
...(data || {}),
secretapikey: this.secretApiKey,
apikey: this.apiKey,
};
res = await axios.post(`${this.baseUrl}${url}`, data);
return res;
}catch(error){
throw new Error(`PorkPun API ${error.response.status}: ${error.response.data.message}`)
}
}
__typeCheck(type){
if(!['A', 'MX', 'CNAME', 'ALIAS', 'TXT', 'NS', 'AAAA', 'SRV', 'TLSA', 'CAA', 'HTTPS', 'SVCB'].includes(type)) throw new Error('PorkBun API: Invalid type passed')
}
__parseName(domain, name){
if(name && !name.endsWith('.'+domain)){
return `${name}.${domain}`
}
return name;
}
async getRecords(domain, options){
let res = await this.post(`/dns/retrieve/${domain}`);
if(!options) return res.data.records;
if(options.type) this.__typeCheck(options.type);
if(options.name) options.name = this.__parseName(domain, options.name);
let records = [];
for(let record of res.data.records){
let matchCount = 0
for(let option in options){
if(record[option] === options[option] && ++matchCount === Object.keys(options).length){
records.push(record)
}
}
}
return records;
}
async createRecord(domain, options){
/*
API values
* type
The type of record being created. Valid types are: A, MX, CNAME, ALIAS, TXT, NS, AAAA, SRV, TLSA, CAA, HTTPS, SVCB
* content
The answer content for the record. Please see the DNS management popup from the domain management console for proper formatting of each record type.
* name - optional
The subdomain for the record being created, not including the domain itself. Leave blank to create a record on the root domain. Use * to create a wildcard record.
* ttl - optional
The time to live in seconds for the record. The minimum and the default is 600 seconds.
* prio - optional
The priority of the record for those that support it.
*/
this.__typeCheck(options.type);
if(!options.content) throw new Error('PorkBun API: `content` key is required for this action')
if(options.name) options.name = this.__parseName(domain, options.name);
let res = this.post(`/dns/create/${domain}`, options);
return res.data;
}
}
module.exports = PorkBun;
if(require.main === module){(async function(){try{
let porkBun = new PorkBun(conf.porkBun.apiKey, conf.porkBun.secretApiKey);
console.log(await porkBun.getRecords('holycore.quest', {type:'NS'}))
}catch(error){
console.log('IIFE Error:', error)
}})()}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment