|
| 1 | +import { DataSource } from '../../dist' |
| 2 | +import { StarbaseApp, StarbaseDBConfiguration } from '../../src/handler' |
| 3 | +import { StarbasePlugin } from '../../src/plugin' |
| 4 | + |
| 5 | +export class StatsPlugin extends StarbasePlugin { |
| 6 | + // Prefix route |
| 7 | + prefix: string = '/_internal/stats' |
| 8 | + // Configuration details about the request and user |
| 9 | + private config?: StarbaseDBConfiguration |
| 10 | + // Data source to run internal RPC queries |
| 11 | + dataSource?: DataSource |
| 12 | + |
| 13 | + constructor() { |
| 14 | + super('starbasedb:stats', { |
| 15 | + requiresAuth: true, |
| 16 | + }) |
| 17 | + } |
| 18 | + |
| 19 | + override async register(app: StarbaseApp) { |
| 20 | + app.use(async (c, next) => { |
| 21 | + this.config = c?.get('config') |
| 22 | + this.dataSource = c?.get('dataSource') |
| 23 | + await next() |
| 24 | + }) |
| 25 | + |
| 26 | + app.get(this.prefix, async (c, next) => { |
| 27 | + // Only admin authorized users are permitted to subscribe to CDC events. |
| 28 | + if (this.config?.role !== 'admin') { |
| 29 | + return new Response('Unauthorized request', { status: 400 }) |
| 30 | + } |
| 31 | + |
| 32 | + // Get stats from internal source |
| 33 | + const stats = await this.dataSource?.rpc.getStatistics() |
| 34 | + const additionalStats = { |
| 35 | + ...stats, |
| 36 | + plugins: this.dataSource?.registry?.currentPlugins(), |
| 37 | + } |
| 38 | + return new Response(JSON.stringify(additionalStats), { |
| 39 | + headers: { |
| 40 | + 'Content-Type': 'application/json', |
| 41 | + }, |
| 42 | + }) |
| 43 | + }) |
| 44 | + } |
| 45 | +} |
0 commit comments