Created
September 23, 2023 19:14
-
-
Save fl0wo/3637d866e621b4cd6e10dc78c032e707 to your computer and use it in GitHub Desktop.
Utility code on how to build and query Timestream db containing candlesticks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {QueryCommand, QueryCommandInput} from "@aws-sdk/client-timestream-query"; | |
export function minDifferenceDates(d1:Date, d2:Date) { | |
const differenceMs = d1.getTime() - d2.getTime(); | |
return Math.abs(differenceMs / (1000 * 60)); | |
} | |
export function minutesAgo(agoMinutes:number) { | |
const now = new Date().getTime(); | |
return Math.round((now - agoMinutes) / (1000 * 60)); | |
} | |
export const getAll = (databaseName:string, databaseTable:string) => { | |
return `SELECT * FROM "${databaseName}"."${databaseTable}"`; | |
}; | |
export const getWhere = (field:string, value:string, cmd='=') => { | |
return `WHERE ${field} ${cmd} '${value}'`; | |
}; | |
export const andTime = (field:string, value:string, cmd='=') => { | |
if (value.includes('NaN')) { | |
return ''; | |
} | |
return `AND ${field} ${cmd} ${value}`; | |
}; | |
export const getGroupBy = (field:string) => { | |
return `GROUP BY ${field}`; | |
}; | |
export const getAllWhere = (databaseName:string, databaseTable:string, filters:Array<{field:string;value:string}>) => { | |
const all = getAll(databaseName, databaseTable); | |
if (filters.length==0) { | |
return all; | |
} | |
const allWheres = filters.map((el)=>{ | |
return el.field + ' = ' + '\''+el.value+ '\''; | |
}).join(' AND '); | |
return all + ' WHERE ' + allWheres; | |
}; | |
export const getWhereBetweenTimeStamps = ( | |
databaseName:string, | |
databaseTable:string, | |
filters:Array<{field:string;value:string}>, | |
msStart:number, | |
msEnd:number):string => { | |
const filtered = getAllWhere(databaseName, databaseTable, filters); | |
if (msEnd<msStart) { | |
throw Error('msEnd<msStart on getWhereBetweenTimeStamps'); | |
} | |
const hoursAgoStart = minutesAgo(msStart); | |
const hoursAgoEnd = minutesAgo(msEnd); | |
return `${filtered} AND time > ago(${hoursAgoStart}m) AND time < ago(${hoursAgoEnd}m)`; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment