Skip to content

Commit

Permalink
Fix Cloudflare Worker Prisma use
Browse files Browse the repository at this point in the history
  • Loading branch information
lemonmade committed Mar 31, 2024
1 parent 0a586ad commit 36b4187
Show file tree
Hide file tree
Showing 15 changed files with 156 additions and 44 deletions.
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,8 @@
},
"[prisma]": {
"editor.defaultFormatter": "Prisma.prisma"
},
"[toml]": {
"editor.defaultFormatter": "tamasfe.even-better-toml"
}
}
90 changes: 90 additions & 0 deletions configuration/rollup/prisma.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import {createHash} from 'node:crypto';

export function prismaFromEdge() {
return [wasm()];
}

// To use Prisma on Workers without their data proxy, I need to use the .wasm version
// of the Prisma client. Cloudflare wants .wasm files to be imported directly in the worker
// script, with a proper relative path, which it then automatically turns into a `WebAssembly.Module`.
// This plugin copies `.wasm` imports, adds a hash for consistency, and replaces the import
// for that file with the new, hashed path.
//
// @see https://developers.cloudflare.com/workers/runtime-apis/webassembly/javascript/
// @see https://developers.cloudflare.com/workers/wrangler/bundling/
// @see https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface
// @see https://github.com/rollup/plugins/blob/master/packages/wasm/src/index.ts
function wasm(options = {}) {
const {fileName = '[name].[hash][extname]'} = options;

const copies = new Map();

return {
name: 'wasm',

async resolveId(id, importer) {
if (!/\.wasm$/.test(id)) {
return null;
}

const resolved = await this.resolve(id, importer, {skipSelf: true});

if (!resolved) {
return null;
}

const file = resolved.id;

const existingCopy = copies.get(file);
if (existingCopy) {
return {
id: existingCopy.filename,
external: true,
};
}

const content = await fs.readFile(file);
const extension = path.extname(file);
const name = path.basename(file, extension);

const hash = createHash('sha1')
.update(content)
.digest('hex')
.substring(0, 8);

const outputFileName = fileName
.replace(/\[hash\]/g, hash)
.replace(/\[ext\]/g, extension.slice(1))
.replace(/\[extname\]/g, extension)
.replace(/\[name\]/g, name);

this.addWatchFile(file);

copies.set(file, {
filename: outputFileName,
content,
});

return {
id: outputFileName,
external: true,
};
},
generateBundle: async function write() {
await Promise.all(
[...copies.values()].map(({filename, content}) => {
this.emitFile({
type: 'asset',
source: content,
name: 'Rollup WASM Asset',
fileName: filename,
});
}),
);
},
};
}

export default wasm;
10 changes: 7 additions & 3 deletions functions/stripe/configuration/rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import {quiltServer} from '@quilted/rollup/server';
import {quiltModule} from '@quilted/rollup/module';
import {cloudflareWorkers} from '@quilted/cloudflare/craft';
import {prismaFromEdge} from '../../../configuration/rollup/prisma.js';

export default quiltServer({
const config = await quiltModule({
entry: './stripe.ts',
format: 'custom',
runtime: cloudflareWorkers(),
});

config.plugins.push(prismaFromEdge());

export default config;
1 change: 0 additions & 1 deletion functions/stripe/configuration/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ account_id = "9bfdb755def60e50760e33036c6f1624"
compatibility_date = "2024-03-29"

logpush = true
node_compat = true
workers_dev = false

[[services]]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import {quiltServer} from '@quilted/rollup/server';
import {quiltModule} from '@quilted/rollup/module';
import {cloudflareWorkers} from '@quilted/cloudflare/craft';
import {prismaFromEdge} from '../../../configuration/rollup/prisma.js';

export default quiltServer({
const config = await quiltModule({
entry: './tmdb-refresher-scheduler.ts',
format: 'custom',
runtime: cloudflareWorkers(),
});

config.plugins.push(prismaFromEdge());

export default config;
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ account_id = "9bfdb755def60e50760e33036c6f1624"
compatibility_date = "2024-03-29"

logpush = true
node_compat = true
workers_dev = false

# @see https://developers.cloudflare.com/workers/wrangler/configuration/#triggers
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ interface Environment {

const scheduled: ExportedHandlerScheduledHandler<Environment> =
async function scheduled(event, env) {
console.log(event);
console.log(JSON.stringify(event, null, 2));

try {
const prisma = await createEdgeDatabaseConnection({
Expand Down
2 changes: 1 addition & 1 deletion functions/tmdb-refresher-scheduler/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
}
},
"include": ["**/*"],
"exclude": ["quilt.project.ts", "build"],
"exclude": ["configuration", "build"],
"references": [{"path": "../tmdb-refresher"}]
}
10 changes: 7 additions & 3 deletions functions/tmdb-refresher/configuration/rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import {quiltServer} from '@quilted/rollup/server';
import {quiltModule} from '@quilted/rollup/module';
import {cloudflareWorkers} from '@quilted/cloudflare/craft';
import {prismaFromEdge} from '../../../configuration/rollup/prisma.js';

export default quiltServer({
const config = await quiltModule({
entry: './tmdb-refresher.ts',
format: 'custom',
runtime: cloudflareWorkers(),
});

config.plugins.push(prismaFromEdge());

export default config;
1 change: 0 additions & 1 deletion functions/tmdb-refresher/configuration/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ account_id = "9bfdb755def60e50760e33036c6f1624"
compatibility_date = "2024-03-29"

logpush = true
node_compat = true
workers_dev = false

# @see https://developers.cloudflare.com/queues/configuration/
Expand Down
4 changes: 1 addition & 3 deletions functions/tmdb-refresher/tmdb-refresher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,7 @@ const handleQueue: ExportedHandlerQueueHandler<Environment, Message> =

export default {fetch: handleFetch, queue: handleQueue};

let prismaPromise:
| Promise<import('@prisma/client/edge').PrismaClient>
| undefined;
let prismaPromise: Promise<import('@prisma/client').PrismaClient> | undefined;

async function createPrisma(url: string) {
prismaPromise ??= createEdgeDatabaseConnection({url});
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@
"@changesets/changelog-github": "^0.4.3",
"@changesets/cli": "^2.26.2",
"@planetscale/database": "^1.16.0",
"@prisma/client": "^5.11.0",
"@prisma/adapter-planetscale": "^5.11.0",
"@prisma/client": "^5.11.0",
"@quilted/browserslist-config": "^0.1.9",
"@quilted/cloudflare": "^0.2.4",
"@quilted/cloudflare": "^0.2.5",
"@quilted/craft": "^0.2.5",
"@quilted/graphql-tools": "^0.2.0",
"@quilted/prettier": "^0.2.11",
"@quilted/quilt": "^0.6.8",
"@quilted/rollup": "^0.2.20",
"@quilted/rollup": "^0.2.22",
"@quilted/typescript": "^0.3.0",
"@quilted/vite": "^0.1.17",
"@types/common-tags": "^1.8.1",
Expand Down
56 changes: 34 additions & 22 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion scripts/tmdb/scratchpad.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'dotenv/config';

// console.log(await tmdbSearch('survivor'));
// console.log(await tmdbSeries({id: 138757}));
// console.log(await tmdbSeries({id: 213810}));

// Utilities

Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"extends": "@quilted/typescript/workspace.json",
"include": ["configuration/**/*.ts", "scripts/**/*.ts", "graphql.config.ts"],
"include": ["configuration/**/*.ts", "**/configuration/**/*.ts", "scripts/**/*.ts", "graphql.config.ts"],
"compilerOptions": {
"outDir": "build/typescript/workspace",
"module": "ESNext",
Expand Down

0 comments on commit 36b4187

Please sign in to comment.