File
Blob: types/test/types/cf.ts
| 1 | // Copyright (c) 2023 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | |
| 5 | function expectType<T>(_value: T) {} |
| 6 | |
| 7 | export const handler: ExportedHandler<{ SERVICE: Fetcher }> = { |
| 8 | async fetch(request, env) { |
| 9 | // Can access incoming cf properties without narrowing |
| 10 | expectType<string | undefined>(request.cf?.colo); |
| 11 | // ...but cannot access request init cf properties |
| 12 | expectType<unknown>(request.cf?.cacheEverything); |
| 13 | |
| 14 | // Can forward request as is (unknown cf properties ignored) |
| 15 | await fetch(request); |
| 16 | |
| 17 | // Can forward request to different URL (unknown cf properties ignored) |
| 18 | await fetch("https://example.com", request); |
| 19 | |
| 20 | // Can fetch with request init cf properties |
| 21 | await fetch("https://example.com", { |
| 22 | cf: { cacheEverything: true }, |
| 23 | }); |
| 24 | |
| 25 | // Can fetch to service binding with incoming properties to simulate incoming request |
| 26 | await env.SERVICE.fetch("https://example.com", { |
| 27 | cf: { colo: "LHR" }, |
| 28 | }); |
| 29 | |
| 30 | // Can fetch to service binding with custom properties |
| 31 | await env.SERVICE.fetch("https://example.com", { |
| 32 | cf: { token: "thing" }, |
| 33 | }); |
| 34 | // ...and can safely access that on the incoming request |
| 35 | expectType<unknown>(request.cf?.token); |
| 36 | if (typeof request.cf?.token === "string") { |
| 37 | expectType<string>(request.cf.token); |
| 38 | } |
| 39 | |
| 40 | return new Response(); |
| 41 | }, |
| 42 | }; |