Skip to content

Commit

Permalink
add AsyncOriginFunction type (#302)
Browse files Browse the repository at this point in the history
  • Loading branch information
sknetl authored May 10, 2024
1 parent 9cc2543 commit e2faab0
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
3 changes: 2 additions & 1 deletion types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type FastifyCorsHook =

declare namespace fastifyCors {
export type OriginFunction = (origin: string | undefined, callback: OriginCallback) => void;
export type AsyncOriginFunction = (origin: string | undefined) => Promise<ValueOrArray<OriginType>>;

export interface FastifyCorsOptions {
/**
Expand All @@ -38,7 +39,7 @@ declare namespace fastifyCors {
/**
* Configures the Access-Control-Allow-Origin CORS header.
*/
origin?: ValueOrArray<OriginType> | fastifyCors.OriginFunction;
origin?: ValueOrArray<OriginType> | fastifyCors.AsyncOriginFunction | fastifyCors.OriginFunction;
/**
* Configures the Access-Control-Allow-Credentials CORS header.
* Set to true to pass the header, otherwise it is omitted.
Expand Down
34 changes: 33 additions & 1 deletion types/index.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import fastify, { FastifyRequest } from 'fastify'
import { expectType } from 'tsd'
import fastifyCors, {
AsyncOriginFunction,
FastifyCorsOptions,
FastifyCorsOptionsDelegate,
FastifyCorsOptionsDelegatePromise,
Expand Down Expand Up @@ -117,6 +118,26 @@ app.register(fastifyCors, {
strictPreflight: false
})

const asyncCorsDelegate: OriginFunction = async (origin) => {
if (origin === undefined || /localhost/.test(origin)) {
return true;
}
return false;
}

app.register(fastifyCors, {
origin: asyncCorsDelegate,
allowedHeaders: ['authorization', 'content-type'],
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
optionsSuccessStatus: 200,
preflight: false,
strictPreflight: false
})

app.register(fastifyCors, {
origin: (origin, cb) => cb(null, true)
})
Expand Down Expand Up @@ -349,7 +370,18 @@ appHttp2.register(fastifyCors, delegate)

appHttp2.register(fastifyCors, {
hook: 'preParsing',
origin: function (origin) {
origin: function (origin, cb) {
expectType<string|undefined>(origin)
cb(null, false)
},
})

const asyncOriginFn: AsyncOriginFunction = async function (origin): Promise<boolean> {
expectType<string|undefined>(origin)
return false;
};

appHttp2.register(fastifyCors, {
hook: 'preParsing',
origin: asyncOriginFn,
})

0 comments on commit e2faab0

Please sign in to comment.