tRPC Adapter
How to set up API routes for Filenest in a tRPC router.
Setup
1. Install dependencies
1npm install @filenest/core @filenest/adapter-trpc @trpc/server
2. Create a router
Just initialize the adapter and add it to your base tRPC router.
import { initTRPC } from "@trpc/server"
import { initTRPCAdapter } from "@filenest/adapter-trpc"
import { Cloudinary } from "@filenest/provider-cloudinary"
const provider = new Cloudinary({...})
const mediaRouter = initTRPCAdapter(provider).create()
const t = initTRPC.create()
const trpcRouter = t.router({
media: mediaRouter,
})
Needs improvement
Currently, the Filenest tRPC router is not very type-safe.
Although not necessary, you might not be able to access the procedures
using @trpc/react-query
or the vanilla client, if you tried to.
Now you're all set to build your UI. Check out the minimal setup to get started.
Middleware
You can add middleware to the procedures to handle authorization, logging, etc.
When creating the router, you can call the use
method before create
to add middleware.
use
takes in two arguments: An array of middlewares that will be applied to all procedures,
and an object with arrays of middlewares that will be applied to specific procedures.
Global middleware
In this first example, a single middleware is added to all procedures.
const helloMiddleware = t.middleware(({ ctx, next }) => {
console.log("hello from middleware. this runs on each request")
return next()
})
const mediaRouter = initTRPCAdapter(provider)
.use([helloMiddleware])
.create()
Scoped middleware
But if you want a middleware to run only on a specific procedure,
just pass in a second argument and define your middleware(s) for that procedure.
const folderMiddleware = t.middleware(({ ctx, next }) => {
console.log("this middleware runs when a folder is created")
return next()
})
// Pass an empty array, if you don't want any global middleware,
// but only scoped middleware.
const mediaRouter = initTRPCAdapter(provider)
.use([], { createFolder: [folderMiddleware] })
.create()
Chaining middleware
You can chain multiple middlewares together by calling use
multiple times.
const helloMiddleware = t.middleware(({ ctx, next }) => {
console.log("hello from middleware. this runs on each request")
return next()
})
const owlMiddleware = t.middleware(({ ctx, next }) => {
console.log("hoo-ray, you've chained middleware!")
return next()
})
const mediaRouter = initTRPCAdapter(provider)
.use([helloMiddleware])
.use([owlMiddleware])
.create()
Custom Procedure
Oftentimes you have different procedures depending on the authentication
requirements of a procedure. You can pass in an arbitrary procedure to be
used for all Filenest tRPC procedures. This can make it easier to apply middleware.
const adminProcedure = t.procedure.use(t.middleware(({ ctx, next }) => {
// do auth checks
return next()
}))
const mediaRouter = initTRPCAdapter(provider)
.procedure(adminProcedure)
.create()