Skip to content

Commit

Permalink
chore: improve types for setHeaders option (#428)
Browse files Browse the repository at this point in the history
  • Loading branch information
EvanHahn committed Jan 26, 2024
1 parent a34d6a2 commit bcf5664
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
11 changes: 9 additions & 2 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Leo <https://github.com/leomelzer>
/// <reference types="node" />

import { FastifyPluginAsync, FastifyRequest, RouteOptions } from 'fastify'
import { FastifyPluginAsync, FastifyReply, FastifyRequest, RouteOptions } from 'fastify'
import { Stats } from 'fs'

declare module 'fastify' {
Expand All @@ -19,6 +19,13 @@ declare module 'fastify' {
type FastifyStaticPlugin = FastifyPluginAsync<NonNullable<fastifyStatic.FastifyStaticOptions>>;

declare namespace fastifyStatic {
export interface SetHeadersResponse {
getHeader: FastifyReply['getHeader'];
setHeader: FastifyReply['header'];
readonly filename: string;
statusCode: number;
}

export interface ExtendedInformation {
fileCount: number;
totalFileCount: number;
Expand Down Expand Up @@ -83,7 +90,7 @@ declare namespace fastifyStatic {
serve?: boolean;
decorateReply?: boolean;
schemaHide?: boolean;
setHeaders?: (...args: any[]) => void;
setHeaders?: (res: SetHeadersResponse, path: string, stat: Stats) => void;
redirect?: boolean;
wildcard?: boolean;
list?: boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat;
Expand Down
14 changes: 11 additions & 3 deletions types/index.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import fastify, { FastifyInstance, FastifyPluginAsync, FastifyRequest } from 'fastify'
import fastify, { FastifyInstance, FastifyPluginAsync, FastifyRequest, FastifyReply } from 'fastify'
import { Server } from 'http'
import { Stats } from 'fs'
import { expectAssignable, expectError, expectType } from 'tsd'
import * as fastifyStaticStar from '..'
import fastifyStatic, {
Expand Down Expand Up @@ -49,8 +50,15 @@ const options: FastifyStaticOptions = {
serve: true,
wildcard: true,
list: false,
setHeaders: (res: any, pathName: any) => {
res.setHeader('test', pathName)
setHeaders: (res, path, stat) => {
expectType<string>(res.filename)
expectType<number>(res.statusCode)
expectType<ReturnType<FastifyReply['getHeader']>>(res.getHeader('X-Test'))
res.setHeader('X-Test', 'string')

expectType<string>(path)

expectType<Stats>(stat)
},
preCompressed: false,
allowedPath: (pathName: string, root: string, request: FastifyRequest) => {
Expand Down

0 comments on commit bcf5664

Please sign in to comment.