openf1-client
Version:
Library for querying data from the OpenF1 API
105 lines (104 loc) • 3.25 kB
JavaScript
const toCamel = (s) => {
return s.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
};
const toSnake = (s) => {
return s.replace(/([A-Z])/g, '_$1').toLowerCase();
};
const isObject = (o) => {
return o === Object(o) && !Array.isArray(o) && typeof o !== 'function';
};
const keysToCamel = (o) => {
if (isObject(o)) {
const n = {};
Object.keys(o).forEach((k) => {
n[toCamel(k)] = keysToCamel(o[k]);
});
return n;
}
else if (Array.isArray(o)) {
return o.map((i) => {
return keysToCamel(i);
});
}
return o;
};
export class OpenF1Client {
constructor(options = {}) {
this.baseURL = 'https://api.openf1.org/v1';
this.camelize = (options.camelize ?? false);
this.debug = options.debug || false;
}
async get(path, query) {
let queryString = '';
if (query) {
const params = Object.fromEntries(Object.entries(query).map(([k, v]) => [toSnake(k), String(v)]));
queryString = '?' + new URLSearchParams(params).toString();
}
if (this.debug) {
console.log(`GET ${this.baseURL}${path}${queryString}`);
}
const response = await fetch(`${this.baseURL}${path}${queryString}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
}
});
if (!response.ok) {
throw new Error(`Error fetching data [${response.status}]: ${response.statusText}`);
}
const data = await response.json();
return (this.camelize ? keysToCamel(data) : data);
}
async getCarData(params) {
return this.get('/car_data', params);
}
async getDrivers(params) {
return this.get('/drivers', params);
}
async getIntervals(params) {
return this.get('/intervals', params);
}
async getLaps(params) {
return this.get('/laps', params);
}
async getLocation(params) {
return this.get('/location', params);
}
async getMeetings(params) {
return this.get('/meetings', params);
}
async getPit(params) {
return this.get('/pit', params);
}
async getPosition(params) {
return this.get('/position', params);
}
async getRaceControl(params) {
return this.get('/race_control', params);
}
async getSessions(params) {
return this.get('/sessions', params);
}
async getSessionResults(params) {
if (this.debug) {
console.warn(`NOTE: Session result is in beta and may change in the future or be removed`);
}
return this.get('/session_result', params);
}
async getStartingGrid(params) {
if (this.debug) {
console.warn(`NOTE: Starting grid is in beta and may change in the future or be removed`);
}
return this.get('/starting_grid', params);
}
async getStints(params) {
return this.get('/stints', params);
}
async getTeamRadio(params) {
return this.get('/team_radio', params);
}
async getWeather(params) {
return this.get('/weather', params);
}
}