neondatabase / serverless

Connect to Neon PostgreSQL from serverless/worker/edge functions
https://www.npmjs.com/package/@neondatabase/serverless
MIT License
343 stars 13 forks source link

Override fetch function for SQL-over-HTTP #34

Closed TimoWilhelm closed 1 year ago

TimoWilhelm commented 1 year ago

Currently the only way to modify the fetch behavior is through the fetchOptions param.

It might also make sense to allow overriding of the fetch function itself. Some SSR frameworks provide alternative fetch functions with additional features or better performance and it could make it easier to extend the fetch behaviour (for example using fetch-retry).

Anyway, the new new SQL-over-HTTP driver looks really promising!

jawj commented 1 year ago

This is a nice idea. I already had vaguely in mind that we should provide something equivalent to the webSocketConstructor option, but for the http case. I'll see to it.

jawj commented 1 year ago

This is released in 0.5.3 and works like this:

import { neonConfig, neon } from '@neondatabase/serverless';

neonConfig.fetchFunction = (url: string, options: any) => {
  console.log('custom fetch:', url, options);
  return fetch(url, options);
};

const sql = neon(process.env.DATABASE_URL);

await sql`SELECT ${"customFetch"} AS str`;

Which logs:

custom fetch: https://ep-xyz.eu-central-1.aws.neon.tech/sql {
  method: 'POST',
  body: '{"query":"SELECT $1 AS str","params":["customFetch"]}',
  headers: {
    'Neon-Connection-String': 'postgres://user:pass@xyz.eu-central-1.aws.neon.tech/main',
    'Neon-Raw-Text-Output': 'true',
    'Neon-Array-Mode': 'true',
    'Neon-Pool-Opt-In': 'true'
  }
}