Last active
August 3, 2023 07:35
-
-
Save rafirh/94ee9f619889033a0b5df8feb2a045af to your computer and use it in GitHub Desktop.
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 type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' | |
import AuthException from 'App/Exceptions/AuthException' | |
import dbConfig from 'Config/database' | |
import Env from '@ioc:Adonis/Core/Env' | |
import Database from '@ioc:Adonis/Lucid/Database'; | |
export default class SwitchDatabase { | |
public async handle({ request }: HttpContextContract, next: () => Promise<void>) { | |
const storeCode = request.header('code-store'); | |
if (!storeCode) { | |
throw new AuthException('Missing code store', 401, 'E_UNAUTHORIZED_ACCESS') | |
} | |
const databaseName = `${Env.get('PG_DB_NAME_PREFIX')}_${storeCode}`; | |
await Database.manager.closeAll() | |
try { | |
dbConfig.connections.pg.connection = { | |
host: Env.get('PG_HOST'), | |
port: Env.get('PG_PORT'), | |
user: Env.get('PG_USER'), | |
password: Env.get('PG_PASSWORD'), | |
database: databaseName, | |
} | |
await Database.rawQuery(`SELECT 1 FROM pg_database WHERE datname = '${databaseName}'`) | |
} catch (error) { | |
throw new AuthException("Invalid store code", 401, 'E_UNAUTHORIZED_ACCESS') | |
} | |
await next() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment