UNPKG

sqlpad

Version:

Web app for writing and running SQL queries and visualizing the results. Supports Postgres, MySQL, SQL Server, Crate and Vertica.

65 lines (58 loc) 1.77 kB
const fetch = require('node-fetch') const NEXT_URI_TIMEOUT = 100 module.exports = { send } // Util - setTimeout as a promise function wait(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } // Get Presto headers from config function getHeaders(config) { const headers = { 'X-Presto-User': config.user } if (config.catalog) { headers['X-Presto-Catalog'] = config.catalog } if (config.schema) { headers['X-Presto-Schema'] = config.schema } return headers } // Given config and query, returns promise with the results function send(config, query) { if (!config.url) { return Promise.reject(new Error('config.url is required')) } const results = { data: [] } return fetch(`${config.url}/v1/statement`, { method: 'POST', body: query, headers: getHeaders(config) }) .then(response => response.json()) .then(statement => handleStatementAndGetMore(results, statement, config)) } function updateResults(results, statement) { if (statement.data && statement.data.length) { results.data = results.data.concat(statement.data) } if (statement.columns) { results.columns = statement.columns } return results } function handleStatementAndGetMore(results, statement, config) { if (statement.error) { console.error(statement.error) // has .errorName and .message results.error = statement.error return Promise.resolve(results) } results = updateResults(results, statement) if (!statement.nextUri) { return Promise.resolve(results) } return wait(NEXT_URI_TIMEOUT) .then(() => fetch(statement.nextUri, { headers: getHeaders(config) })) .then(response => response.json()) .then(statement => handleStatementAndGetMore(results, statement, config)) }