Skip to content

Commit

Permalink
Checking if the db url env is a valid URL
Browse files Browse the repository at this point in the history
  • Loading branch information
jamiehewitt15 committed Aug 12, 2024
1 parent abdfaed commit a1e46f2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 20 deletions.
42 changes: 23 additions & 19 deletions src/components/database/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { DATABASE_LOGGER } from '../../utils/logging/common.js'
import { validateObject } from '../core/utils/validateDdoHandler.js'
import { ENVIRONMENT_VARIABLES, TYPESENSE_HITS_CAP } from '../../utils/constants.js'
import { SQLiteProvider } from './sqlite.js'
import { URLUtils } from '../../utils/url.js'

export class OrderDatabase {
private provider: Typesense
Expand Down Expand Up @@ -616,27 +617,30 @@ export class NonceDatabase {
private schema: Schema
) {
return (async (): Promise<NonceDatabase> => {
try {
this.provider = new Typesense({
...convertTypesenseConfig(this.config.url),
logger: DATABASE_LOGGER
})
await this.provider.collections(this.schema.name).retrieve()
} catch (error) {
if (error instanceof TypesenseError && error.httpStatus === 404) {
await (this.provider as Typesense).collections().create(this.schema)
} else {
// Fall back to SQLite
DATABASE_LOGGER.logMessageWithEmoji(
'Typesense not available, falling back to SQLite',
true,
GENERIC_EMOJIS.EMOJI_CROSS_MARK,
LOG_LEVELS_STR.LEVEL_WARN
)
this.provider = new SQLiteProvider('nonceDatabase.sqlite')
await this.provider.createTable()
if (this.config.url && URLUtils.isValidUrl(this.config.url)) {
try {
this.provider = new Typesense({
...convertTypesenseConfig(this.config.url),
logger: DATABASE_LOGGER
})
await this.provider.collections(this.schema.name).retrieve()
} catch (error) {
if (error instanceof TypesenseError && error.httpStatus === 404) {
await (this.provider as Typesense).collections().create(this.schema)
}
}
} else {
// Fall back to SQLite
DATABASE_LOGGER.logMessageWithEmoji(
'Typesense not available, falling back to SQLite',
true,
GENERIC_EMOJIS.EMOJI_CROSS_MARK,
LOG_LEVELS_STR.LEVEL_WARN
)
this.provider = new SQLiteProvider('nonceDatabase.sqlite')
await this.provider.createTable()
}

return this
})() as unknown as NonceDatabase
}
Expand Down
2 changes: 1 addition & 1 deletion src/test/integration/database.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ describe('NonceDatabase CRUD with SQLite', () => {
before(async () => {
const dbConfig = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
url: null as null // Empty URL to simulate no Typesense. Using SQLite instead
url: ''
}
database = await new Database(dbConfig)
})
Expand Down

0 comments on commit a1e46f2

Please sign in to comment.