Skip to content

Instantly share code, notes, and snippets.

@rafirh
Last active August 3, 2023 07:35
Show Gist options
  • Save rafirh/94ee9f619889033a0b5df8feb2a045af to your computer and use it in GitHub Desktop.
Save rafirh/94ee9f619889033a0b5df8feb2a045af to your computer and use it in GitHub Desktop.
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