Fix building static sites with Astro DB (#10655)

* Fix building static sites with Astro DB

* Adding a changeset

* Try a different port range
This commit is contained in:
Matthew Phillips 2024-04-02 16:07:18 -04:00 committed by GitHub
parent a79e6b12fa
commit b1eda3dc5c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 128 additions and 3 deletions

View file

@ -0,0 +1,5 @@
---
"@astrojs/db": patch
---
Pass through appToken on static sites with Astro DB

View file

@ -45,6 +45,7 @@ export async function cmd({
tables: dbConfig.tables ?? {}, tables: dbConfig.tables ?? {},
appToken: appToken.token, appToken: appToken.token,
isBuild: false, isBuild: false,
output: 'server',
}); });
} else { } else {
virtualModContents = getLocalVirtualModContents({ virtualModContents = getLocalVirtualModContents({

View file

@ -59,6 +59,7 @@ function astroDBIntegration(): AstroIntegration {
tables, tables,
root: config.root, root: config.root,
srcDir: config.srcDir, srcDir: config.srcDir,
output: config.output,
}); });
} else { } else {
dbPlugin = vitePluginDb({ dbPlugin = vitePluginDb({
@ -67,6 +68,7 @@ function astroDBIntegration(): AstroIntegration {
seedFiles, seedFiles,
root: config.root, root: config.root,
srcDir: config.srcDir, srcDir: config.srcDir,
output: config.output,
}); });
} }

View file

@ -4,6 +4,7 @@ import { SEED_DEV_FILE_NAME } from '../../runtime/queries.js';
import { DB_PATH, RUNTIME_CONFIG_IMPORT, RUNTIME_IMPORT, VIRTUAL_MODULE_ID } from '../consts.js'; import { DB_PATH, RUNTIME_CONFIG_IMPORT, RUNTIME_IMPORT, VIRTUAL_MODULE_ID } from '../consts.js';
import type { DBTables } from '../types.js'; import type { DBTables } from '../types.js';
import { type VitePlugin, getDbDirectoryUrl, getRemoteDatabaseUrl } from '../utils.js'; import { type VitePlugin, getDbDirectoryUrl, getRemoteDatabaseUrl } from '../utils.js';
import type { AstroConfig } from 'astro';
const WITH_SEED_VIRTUAL_MODULE_ID = 'astro:db:seed'; const WITH_SEED_VIRTUAL_MODULE_ID = 'astro:db:seed';
@ -26,6 +27,7 @@ type VitePluginDBParams =
seedFiles: LateSeedFiles; seedFiles: LateSeedFiles;
srcDir: URL; srcDir: URL;
root: URL; root: URL;
output: AstroConfig['output'];
} }
| { | {
connectToStudio: true; connectToStudio: true;
@ -33,6 +35,7 @@ type VitePluginDBParams =
appToken: string; appToken: string;
srcDir: URL; srcDir: URL;
root: URL; root: URL;
output: AstroConfig['output'];
}; };
export function vitePluginDb(params: VitePluginDBParams): VitePlugin { export function vitePluginDb(params: VitePluginDBParams): VitePlugin {
@ -66,6 +69,7 @@ export function vitePluginDb(params: VitePluginDBParams): VitePlugin {
appToken: params.appToken, appToken: params.appToken,
tables: params.tables.get(), tables: params.tables.get(),
isBuild: command === 'build', isBuild: command === 'build',
output: params.output,
}); });
} }
return getLocalVirtualModContents({ return getLocalVirtualModContents({
@ -141,15 +145,22 @@ export function getStudioVirtualModContents({
tables, tables,
appToken, appToken,
isBuild, isBuild,
output,
}: { }: {
tables: DBTables; tables: DBTables;
appToken: string; appToken: string;
isBuild: boolean; isBuild: boolean;
output: AstroConfig['output'];
}) { }) {
function appTokenArg() { function appTokenArg() {
if (isBuild) { if (isBuild) {
if(output === 'server') {
// In production build, always read the runtime environment variable. // In production build, always read the runtime environment variable.
return 'process.env.ASTRO_STUDIO_APP_TOKEN'; return 'process.env.ASTRO_STUDIO_APP_TOKEN';
} else {
// Static mode or prerendering needs the local app token.
return `process.env.ASTRO_STUDIO_APP_TOKEN ?? ${JSON.stringify(appToken)}`;
}
} else { } else {
return JSON.stringify(appToken); return JSON.stringify(appToken);
} }

View file

@ -0,0 +1,6 @@
import astroDb from '@astrojs/db';
import { defineConfig } from 'astro/config';
export default defineConfig({
integrations: [astroDb()],
});

View file

@ -0,0 +1,12 @@
import { column, defineDb, defineTable } from 'astro:db';
const User = defineTable({
columns: {
id: column.number({ primaryKey: true }),
name: column.text(),
},
});
export default defineDb({
tables: { User },
});

View file

@ -0,0 +1,9 @@
import { User, db } from 'astro:db';
export default async function () {
await db.insert(User).values([
{
name: 'Houston'
}
]);
}

View file

@ -0,0 +1,16 @@
{
"name": "@test/db-static-remote",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@astrojs/db": "workspace:*",
"astro": "workspace:*"
}
}

View file

@ -0,0 +1,20 @@
---
import { User, db } from 'astro:db';
const users = await db.select().from(User);
---
<html>
<head>
<title>Testing</title>
</head>
<body>
<h1>Testing</h1>
<h2>Users</h2>
<ul>
{users.map(user => (
<li>{user.name}</li>
))}
</ul>
</body>
</html>

View file

@ -0,0 +1,34 @@
import { expect } from 'chai';
import { load as cheerioLoad } from 'cheerio';
import { loadFixture } from '../../astro/test/test-utils.js';
import { setupRemoteDbServer } from './test-utils.js';
describe('astro:db', () => {
let fixture;
before(async () => {
fixture = await loadFixture({
root: new URL('./fixtures/static-remote/', import.meta.url),
output: 'static',
});
});
describe('static build --remote', () => {
let remoteDbServer;
before(async () => {
remoteDbServer = await setupRemoteDbServer(fixture.config);
await fixture.build();
});
after(async () => {
await remoteDbServer?.stop();
});
it('Can render page', async () => {
const html = await fixture.readFile('/index.html');
const $ = cheerioLoad(html);
expect($('li').length).to.equal(1);
});
});
});

View file

@ -12,7 +12,7 @@ const singleQuerySchema = z.object({
const querySchema = singleQuerySchema.or(z.array(singleQuerySchema)); const querySchema = singleQuerySchema.or(z.array(singleQuerySchema));
let portIncrementer = 8081; let portIncrementer = 8030;
/** /**
* @param {import('astro').AstroConfig} astroConfig * @param {import('astro').AstroConfig} astroConfig

9
pnpm-lock.yaml generated
View file

@ -3996,6 +3996,15 @@ importers:
specifier: workspace:* specifier: workspace:*
version: link:../../../../astro version: link:../../../../astro
packages/db/test/fixtures/static-remote:
dependencies:
'@astrojs/db':
specifier: workspace:*
version: link:../../..
astro:
specifier: workspace:*
version: link:../../../../astro
packages/db/test/fixtures/ticketing-example: packages/db/test/fixtures/ticketing-example:
dependencies: dependencies:
'@astrojs/check': '@astrojs/check':