Sink/server/api/stats/views.get.ts
wudi 7cadbfe2b1 refactor: Migrate project files and directories to the app directory using the new compatibilityVersion: 4 feature
- Moved `app.config.ts` to the `app` directory
- Migrated `.vue` files and other assets to the `app` directory
- Updated import paths to reflect the new file locations
2025-03-24 11:05:59 +08:00

29 lines
1,004 B
TypeScript

import type { H3Event } from 'h3'
import { QuerySchema } from '@@/schemas/query'
import { z } from 'zod'
const { select } = SqlBricks
const unitMap: { [x: string]: string } = {
hour: '%Y-%m-%d %H',
day: '%Y-%m-%d',
}
const ViewsQuerySchema = QuerySchema.extend({
unit: z.string(),
clientTimezone: z.string().default('Etc/UTC'),
})
function query2sql(query: z.infer<typeof ViewsQuerySchema>, event: H3Event): string {
const filter = query2filter(query)
const { dataset } = useRuntimeConfig(event)
const sql = select(`formatDateTime(timestamp, '${unitMap[query.unit]}', '${query.clientTimezone}') as time, SUM(_sample_interval) as visits, COUNT(DISTINCT ${logsMap.ip}) as visitors`).from(dataset).where(filter).groupBy('time').orderBy('time')
appendTimeFilter(sql, query)
return sql.toString()
}
export default eventHandler(async (event) => {
const query = await getValidatedQuery(event, ViewsQuerySchema.parse)
const sql = query2sql(query, event)
return useWAE(event, sql)
})