Skip to content

Commit

Permalink
add a cf field to the getBindingsProxy result
Browse files Browse the repository at this point in the history
  • Loading branch information
dario-piotrowicz committed Feb 5, 2024
1 parent 5ef5606 commit 431af33
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
16 changes: 16 additions & 0 deletions .changeset/strong-otters-hope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
"wrangler": minor
---

feature: add a `cf` field to the `getBindingsProxy` result

Add a new `cf` filed to the `getBindingsProxy` result that people can use to mock the production
`cf` (`IncomingRequestCfProperties`) object.

Example:

```ts
const { cf } = await getBindingsProxy();

console.log(`country = ${cf.country} ; colo = ${cf.colo}`); // logs 'country = GB ; colo = LHR'
```
38 changes: 38 additions & 0 deletions fixtures/get-bindings-proxy/tests/get-bindings-proxy.cf.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import { getBindingsProxy } from "./shared";

describe("getBindingsProxy - cf", () => {
it("should provide mock data", async () => {
const { cf, dispose } = await getBindingsProxy();
try {
expect(cf).toMatchObject({
colo: "DFW",
city: "Austin",
regionCode: "TX",
});
} finally {
await dispose();
}
});

it("should match the production runtime cf object", async () => {
const { cf, dispose } = await getBindingsProxy();
try {
expect(cf.constructor.name).toBe("Object");

expect(() => {
cf.city = "test city";
}).toThrowError(
"Cannot assign to read only property 'city' of object '#<Object>'"
);
expect(cf.city).not.toBe("test city");

expect(() => {
cf.newField = "test new field";
}).toThrowError("Cannot add property newField, object is not extensible");
expect("newField" in cf).toBe(false);
} finally {
await dispose();
}
});
});
6 changes: 6 additions & 0 deletions packages/wrangler/src/api/integrations/bindings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ export type BindingsProxy<Bindings = Record<string, unknown>> = {
* Object containing the various proxies
*/
bindings: Bindings;
/**
* Mock of the context object that Workers received in their request handler, all the object's methods are no-op
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
cf: Record<string, any>;
/**
* Mock of the context object that Workers received in their request handler, all the object's methods are no-op
*/
Expand Down Expand Up @@ -93,6 +98,7 @@ export async function getBindingsProxy<Bindings = Record<string, unknown>>(
...vars,
...bindings,
},
cf: Object.freeze(await mf.getCf()),
ctx: new ExecutionContext(),
caches: new CacheStorage(),
dispose: () => mf.dispose(),
Expand Down

0 comments on commit 431af33

Please sign in to comment.