jpbrown84
12/29/2023, 10:27 AMconst response = await fetch(env.ENDPOINT, {
method: "POST",
headers: {
Authorization: `Basic ${btoa(
`someKey`
)}]`,
"Content-Type": "application/x-www-form-urlencoded"
},
body: "someBody"
});
I'm trying to write a 'testData.test.ts' file to check that fetch was called with the correct args.
If I was working with a node environment i'd just mock out node-fetch and check what the mock was called with.
With the worker, fetch is global, so I have no idea what to mock.
Any help with this would be much appreciatedDannyDanDan
12/29/2023, 10:39 PMwillin
12/30/2023, 11:17 AM- name: Deploy API Service
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CF_API_TOKEN }}
command: publish --config wrangler.toml
workingDirectory: apps/sso
secrets: |
AFDIAN_CLIENT_ID
AFDIAN_CLIENT_SECRET
AFDIAN_CALLBACK_URL
ALIPAY_APP_ID
ALIPAY_PRIVATE_KEY
ALIPAY_CALLBACK_URL
GITHUB_ID
GITHUB_SECRET
SESSION_SECRET
# SESSION_KEY
# GITHUB_CALLBACK_URL
env:
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }}
AFDIAN_CLIENT_ID: ${{ secrets.AFDIAN_CLIENT_ID }}
AFDIAN_CLIENT_SECRET: ${{ secrets.AFDIAN_CLIENT_SECRET }}
AFDIAN_CALLBACK_URL: ${{ secrets.AFDIAN_CALLBACK_URL }}
ALIPAY_APP_ID: ${{ secrets.ALIPAY_APP_ID }}
ALIPAY_PRIVATE_KEY: ${{ secrets.ALIPAY_PRIVATE_KEY }}
ALIPAY_CALLBACK_URL: ${{ secrets.ALIPAY_CALLBACK_URL }}
GITHUB_ID: ${{ secrets.GH_CLIENT_ID }}
GITHUB_SECRET: ${{ secrets.GH_CLIENT_SECRET }}
SESSION_SECRET: ${{ secrets.SESSION_SECRET }}
# SESSION_KEY: ${{ secrets.SESSION_KEY }}
# GITHUB_CALLBACK_URL: ${{ secrets.GITHUB_CALLBACK_URL }}
PoisnFang
12/31/2023, 3:08 AMyigalavi
12/31/2023, 8:53 AMconst corsHeaders = new Headers({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Authorization, Content-Type',
'Content-Type': 'application/json',
});
But I get responses without "Content-Length". do I have to add it manually? is the existence of 'Content-Type': 'application/json' make it so the length isn't added?spuckwaffel
12/31/2023, 11:56 AMjs
const { results } = await env.DB.prepare('SELECT * FROM user').all();
const json = await Response.json(results);
const jjson = JSON.stringify(json);
console.log(jjson);
and yes, the DB is called user, the environment variable in the settings is DB.
Am i missing something?<Evie.Codes>
01/01/2024, 10:40 PMserialize-javascript
to be able to stringify structures beyond what JSON.stringify(). Specifically, serialize-javascript allows for serializing dates, maps, sets, functions, regex and bigint. However, it doesn't provide any deserialize method, and simple states to use eval(). Which works perfectly well and has for years... but trying to port my db wrapper to a worker-supported version has cause me a fair share of grief.
I would rather not remove functionality from my module due to this limitation, though I do understand that the distinction is that the context of running in a worker means we're not only dependendent on the user's system and security, but yours.Joey
01/02/2024, 10:25 PMNikil
01/03/2024, 12:05 AMtelgareith
01/03/2024, 1:00 PMcodeoholic
01/03/2024, 2:29 PMsnowcode
01/03/2024, 4:18 PMts
it('Must be able to create mock Request with cf user init', function() {
const user : IncomingRequestCfProperties = TestUsers.cfCambridgeUser
const init : RequestInit = {
method: 'GET',
cf: user
};
const newRequest = new Request('https://example.com', init);
// Check if cf properties are set
console.log(">>> newRequest.cf >>>" , newRequest.cf);
assert.ok(newRequest.cf!==undefined)
})
This should pass; but the value get's removed (undefined) after it's been set/requested via RequestInit. (ignored)
Here's the definition for RequestInit; in CF's worker-types package
ts
interface RequestInit {
method?: string;
headers?: HeadersInit;
body?: BodyInit | null;
redirect?: string;
fetcher?: Fetcher | null;
/**
* cf is a union of these two types because there are multiple
* scenarios in which it might be one or the other.
*
* IncomingRequestCfProperties is required to allow
* new Request(someUrl, event.request)
*
* RequestInitCfProperties is required to allow
* new Request(event.request, {cf: { ... } })
* fetch(someUrl, {cf: { ... } })
*/
cf?: IncomingRequestCfProperties | RequestInitCfProperties;
signal?: AbortSignal | null;
}
Does anyone know how to create a mock or real Request** using RequestInit?**
Thanks in avance, Alzavierbythebeach
01/03/2024, 4:39 PM*website.com/images*
The following works:
https://website.com/images
but the following does NOT work:
https://www.website.com/images
I've looked at any and all transform, redirect rules. Other workers that may have a conflicting route and nothing appears to be in place that would interfere with this route. Any assistance would be appreciated. Thank you!thisisntme.
01/03/2024, 4:51 PMts
export interface Env {
COUNTER: DurableObjectNamespace;
}
// Worker code:
export default {
async fetch(request: Request, env: Env) {
let url = new URL(request.url);
let name = url.searchParams.get('name');
if (!name) {
return new Response('Select a Durable Object to contact by using' + ' the `name` URL query string parameter, for example, ?name=A');
}
let id = env.COUNTER.idFromName(name);
// Construct the stub for the Durable Object using the ID.
// A stub is a client Object used to send messages to the Durable Object.
let obj = env.COUNTER.get(id);
// Send a request to the Durable Object, then await its response.
return obj.fetch(url);
},
};
// Durable Object
export class Counter {
state: DurableObjectState;
webSockets: Set<WebSocket>;
constructor(state: DurableObjectState, env: Env) {
this.state = state;
this.webSockets = new Set();
}
// Define the broadcast function
broadcast(message: string) {
this.webSockets.forEach((ws) => {
ws.send(message);
});
}
// Handle requests sent to the Durable Object
async fetch(request: Request) {
// Apply requested action.
let url = new URL(request.url);
// Check for websocket request
console.log('DURABLE OBJECT', request.headers.get('Upgrade'));
if (request.headers.get('Upgrade') === 'websocket') {
const pair = new WebSocketPair();
const { 0: clientWebSocket, 1: serverWebSocket } = pair;
serverWebSocket.accept();
this.webSockets.add(serverWebSocket);
let value = Number((await this.state.storage.get('value')) || 0);
serverWebSocket.send(JSON.stringify({ value }));
// Handle websocket messages from the client as the server
serverWebSocket.addEventListener('message', async (event) => {
let data;
if (typeof event.data !== 'string') {
serverWebSocket.send(JSON.stringify({ error: 'Invalid message format' }));
return;
}
try {
data = JSON.parse(event.data);
} catch (error) {
serverWebSocket.send(JSON.stringify({ error: 'Invalid JSON' }));
return;
}
let value = Number((await this.state.storage.get('value')) || 0);
switch (data.command) {
case 'increment':
value++;
break;
case 'decrement':
value--;
break;
default:
serverWebSocket.send(JSON.stringify({ error: 'Unknown command' }));
return;
}
await this.state.storage.put('value', value);
// Broadcast the updated value to all clients
this.broadcast(JSON.stringify({ value }));
});
// Remove the server websocket when it is closed
serverWebSocket.addEventListener('close', (event) => {
this.webSockets.delete(serverWebSocket);
});
// return the client websocket
return new Response(null, { status: 101, webSocket: clientWebSocket });
}
}
}
thisisntme.
01/03/2024, 7:02 PMts
state: DurableObjectState;
webSockets: Set<WebSocket>;
storage: DurableObjectStorage;
constructor(state: DurableObjectState, env: Env) {
this.state = state;
this.storage = state.storage;
this.webSockets = new Set();
}
I guess I'd want to define the type of stuff accessed through this.storage.get()/set()Infinity Chief ∞ I WONT DM YOU
01/03/2024, 10:03 PMhazemhazem999
01/04/2024, 1:01 AMhkhl.
01/04/2024, 12:41 PMHTTP 415 Unsupported Media type
and Cf-resized: err=9412
long after the origin image upload is complete (~ 60 min.) The only way to fix this is to purge the complete cache in the dashboard manually.
I did a lot of debugging, and I don't see why Cloudflare does not revalidate the origin.
- There is no custom caching in the worker
- The origin does not send cache-control headers.
- Manually purging a single upstream URL as described here https://developers.cloudflare.com/images/image-resizing/troubleshooting/#caching-and-purging does not work. (So it is some kind of cache issue)ranjan_mangla
01/04/2024, 5:24 PMJoey
01/05/2024, 8:37 AMjubu02
01/05/2024, 2:16 PMmitya2364
01/05/2024, 6:26 PM/.wrangler/tmp/dev-BjjrCX/index.js
not my/original/file.js
). Thanks.mitya2364
01/05/2024, 6:51 PMError: Connection terminated unexpectedly
from Postgres.
This only happens when using the DB within Wrangler. I have another, non-Wrangler app that connects to the same DB in the same way and via the same connection string, and it's fine. The DB is up, and showing no signs of issues.
Here's the util my controllers call to connect to and run a query on my DB:
export const query = async (q, params) => {
const client = new Client({
connectionString: env[env.DB+'-db'].connectionString,
ssl: {rejectUnauthorized: false}
});
await client.connect();
const res = await client.query(q, params);
return res;
};
The DB connection string is in my TOML under [[Hyperdrive]]
.
If I console.log(client)
right after connecting, it shows readyForQuery: true
. But when I then run a query, I get this error.
Sorry if this is not related to Wrangler but as I say, it's not happening in non-Wrangler setups with the same DB connection code.
Any idea what might be up?rinal_43161
01/05/2024, 7:06 PMherwork
01/05/2024, 9:19 PMKTibow
01/07/2024, 12:07 AMsaraikium
01/07/2024, 5:36 AMbbg0x
01/07/2024, 4:28 PMrodbs
01/07/2024, 4:31 PM{
'$$mdtype': 'Tag',
name: 'Counter',
attributes: [Object],
children: []
}
But on deploying to Pages I get an error
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
and the console:
{
'$$mdtype': 'Tag',
name: '_R',
attributes: [Object],
children: []
}
So it's like the render is working locally and not online.
I've spotted the 'rendering error' in the transform
method:
const ast = parse(markdown)
const config = {
tags: { counter, },
}
return transform(ast, config)
`
What else can I do to debug it? Is the bug in Worker backend?? (because Markdoc works ok locally)s.x.m
01/07/2024, 6:22 PMpathname
?