Skip to content

Commit 054fec1

Browse files
committed
Added an optional generic type to API routes to enforce the return type
1 parent 340b3ab commit 054fec1

File tree

4 files changed

+16
-3
lines changed

4 files changed

+16
-3
lines changed

apps/web/src/middlewares/adminHandler.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { getCurrentUserOrRedirect } from '$/services/auth/getCurrentUser'
22
import { notFound } from 'next/navigation'
33
import { NextRequest } from 'next/server'
4+
import { RouteHandler } from './types'
45

5-
export function adminHandler(handler: any) {
6+
export function adminHandler<T>(handler: RouteHandler<T>) {
67
return async (
78
req: NextRequest,
89
{ params, ...rest }: { params?: Promise<Record<string, string>> } = {},

apps/web/src/middlewares/authHandler.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { getDataFromSession } from '$/data-access'
22
import { NextRequest, NextResponse } from 'next/server'
3+
import { RouteHandler } from './types'
34

4-
export function authHandler(handler: any) {
5+
export function authHandler<T>(handler: RouteHandler<T>) {
56
return async (
67
req: NextRequest,
78
{

apps/web/src/middlewares/errorHandler.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { env } from '@latitude-data/env'
33
import { captureException } from '$/helpers/captureException'
44
import { NextRequest, NextResponse } from 'next/server'
55
import debug from '@latitude-data/core/lib/debug'
6+
import { RouteHandler } from './types'
67

78
interface AbortError extends DOMException {
89
name: 'AbortError'
@@ -18,7 +19,7 @@ export function isAbortError(error: unknown): error is AbortError {
1819
)
1920
}
2021

21-
export function errorHandler(handler: any) {
22+
export function errorHandler<T>(handler: RouteHandler<T>) {
2223
const isDev = env.NODE_ENV === 'development'
2324
return async (req: NextRequest, res: any) => {
2425
try {

apps/web/src/middlewares/types.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { NextRequest, NextResponse } from 'next/server'
2+
3+
type ApiErrorResponse = {
4+
message: string
5+
}
6+
7+
export type RouteHandler<T> = (
8+
req: NextRequest,
9+
res: any,
10+
) => Promise<NextResponse<T> | NextResponse<ApiErrorResponse>>

0 commit comments

Comments
 (0)