spidio-url-shortener
Version:
A Node.js client for Spid.io URL shortening service
91 lines (82 loc) • 2.3 kB
JavaScript
const axios = require('axios');
/**
* Resolves a shortened URL to get the original URL
* @param {Object} options - Configuration options
* @param {string} options.host - API host
* @param {string} options.key - API key
* @param {string} options.auth - Bearer token
* @param {string} options.project - Project identifier
* @returns {Promise<Object>} Promise that resolves to the URL data
*/
async function resolveUrl(options) {
try {
const config = {
headers: {
Host: options.host,
"Content-type": "application/json",
Authorization: `Basic ${options.auth}`,
Accept: "application/json",
"Accept-Charset": "utf-8",
},
};
const response = await axios.get(`https://${options.project}.spid.io/v1/resolve`, config);
return { data: response.data.data };
} catch (error) {
throw new Error(`Failed to resolve URL: ${error.message}`);
}
}
/**
* Creates a shortened URL
* @param {Object} options - Configuration options
* @param {string} options.host - API host
* @param {string} options.key - API key
* @param {string} options.auth - Bearer token
* @param {string} options.project - Project identifier
* @param {Object} data - URL data to shorten
* @returns {Promise<Object>} Promise that resolves to the shortened URL data
*/
async function createShortUrl(options, data) {
try {
const config = {
headers: {
Host: options.host,
"Content-type": "application/json",
Authorization: `Basic ${options.auth}`,
Accept: "application/json",
"Accept-Charset": "utf-8",
},
};
const response = await axios.post(
`https://${options.project}.spid.io/api/v1/shorten`,
data,
config
);
return { data: response.data };
} catch (error) {
return {
data: {
message: 'Unable to create short link',
error: error.message
}
};
}
}
/**
* SpidioUrlShortener class for easier usage
*/
class SpidioUrlShortener {
constructor(options) {
this.options = options;
}
async resolve() {
return resolveUrl(this.options);
}
async shorten(data) {
return createShortUrl(this.options, data);
}
}
module.exports = {
resolveUrl,
createShortUrl,
SpidioUrlShortener
};