@thrustcurve/api1
Version:
TypeScript client for the ThrustCurve.org API
90 lines (89 loc) • 2.79 kB
JavaScript
function decodeBase64(base64String) {
if (typeof window === 'undefined') {
// Node.js environment
return Buffer.from(base64String, 'base64').toString('utf-8');
}
else {
// Browser environment
return new TextDecoder().decode(Uint8Array.from(atob(base64String), c => c.charCodeAt(0)));
}
}
export class ThrustCurveAPI {
baseUrl;
constructor(baseUrl = 'https://www.thrustcurve.org/api/v1') {
this.baseUrl = baseUrl;
}
async request(endpoint, method, data) {
let requestUrl = `${this.baseUrl}/${endpoint}`;
const options = {
method,
headers: {
'Content-Type': 'application/json',
},
};
if (data) {
if (method === 'GET') {
const params = new URLSearchParams();
Object.entries(data).forEach(([key, value]) => {
if (value !== undefined) {
params.append(key, String(value));
}
});
const queryString = params.toString();
if (queryString) {
requestUrl += `?${queryString}`;
}
}
else {
options.body = JSON.stringify(data);
}
}
const response = await fetch(requestUrl, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
/**
* Get metadata about motors in the database
*/
async metadata(criteria = {}) {
return this.request('metadata.json', 'GET', criteria);
}
/**
* Search for motors by various criteria
*/
async searchMotors(criteria) {
return this.request('search.json', 'POST', criteria);
}
/**
* Download simulator files for specific motors
*/
async downloadMotorData(request) {
const response = await this.request('download.json', 'POST', request);
// Decode base64 data in results
response.results = response.results.map(result => ({
...result,
data: result.data ? decodeBase64(result.data) : undefined
}));
return response;
}
/**
* Get saved rockets for an account
*/
async getRockets(credentials) {
return this.request('getrockets.json', 'POST', credentials);
}
/**
* Save rockets to an account
*/
async saveRockets(request) {
return this.request('saverockets.json', 'POST', request);
}
/**
* Get motor recommendations for a specific rocket
*/
async motorGuide(request) {
return this.request('motorguide.json', 'POST', request);
}
}