Elffuss BraidHub

kikocis/lancedb public

b5f7336ae52e · 1.9 KiBRawPermalink
1// Copyright 2023 LanceDB Developers.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15export type Literal = string | number | boolean | null | Date | Literal[]
16
17export function toSQL (value: Literal): string {
18 if (typeof value === 'string') {
19 return `'${value}'`
20 }
21
22 if (typeof value === 'number') {
23 return value.toString()
24 }
25
26 if (typeof value === 'boolean') {
27 return value ? 'TRUE' : 'FALSE'
28 }
29
30 if (value === null) {
31 return 'NULL'
32 }
33
34 if (value instanceof Date) {
35 return `'${value.toISOString()}'`
36 }
37
38 if (Array.isArray(value)) {
39 return `[${value.map(toSQL).join(', ')}]`
40 }
41
42 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
43 throw new Error(`Unsupported value type: ${typeof value} value: (${value})`)
44}
45
46export class TTLCache {
47 private readonly cache: Map<string, { value: any, expires: number }>
48
49 /**
50 * @param ttl Time to live in milliseconds
51 */
52 constructor (private readonly ttl: number) {
53 this.cache = new Map()
54 }
55
56 get (key: string): any | undefined {
57 const entry = this.cache.get(key)
58 if (entry === undefined) {
59 return undefined
60 }
61
62 if (entry.expires < Date.now()) {
63 this.cache.delete(key)
64 return undefined
65 }
66
67 return entry.value
68 }
69
70 set (key: string, value: any): void {
71 this.cache.set(key, { value, expires: Date.now() + this.ttl })
72 }
73
74 delete (key: string): void {
75 this.cache.delete(key)
76 }
77}