Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

db: Seed on dev server startup #10599

Merged
merged 6 commits into from
Apr 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/clever-moles-listen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@astrojs/db": patch
---

Seed database on dev server startup, and log whenever the seed file is reloaded.
58 changes: 48 additions & 10 deletions packages/db/src/core/integration/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ import { type ManagedAppToken, getManagedAppTokenOrExit } from '../tokens.js';
import { type VitePlugin, getDbDirectoryUrl } from '../utils.js';
import { fileURLIntegration } from './file-url.js';
import { typegenInternal } from './typegen.js';
import { type LateSeedFiles, type LateTables, vitePluginDb } from './vite-plugin-db.js';
import { type LateSeedFiles, type LateTables, vitePluginDb, resolved } from './vite-plugin-db.js';
import { vitePluginInjectEnvTs } from './vite-plugin-inject-env-ts.js';
import { SEED_DEV_FILE_NAME } from '../../runtime/queries.js';

function astroDBIntegration(): AstroIntegration {
let connectToStudio = false;
Expand Down Expand Up @@ -94,15 +95,7 @@ function astroDBIntegration(): AstroIntegration {

await typegenInternal({ tables: tables.get() ?? {}, root: config.root });
},
'astro:server:start': async ({ logger }) => {
// Wait for the server startup to log, so that this can come afterwards.
setTimeout(() => {
logger.info(
connectToStudio ? 'Connected to remote database.' : 'New local database created.'
);
}, 100);
},
'astro:server:setup': async ({ server }) => {
'astro:server:setup': async ({ server, logger }) => {
const filesToWatch = [
...CONFIG_FILE_NAMES.map((c) => new URL(c, getDbDirectoryUrl(root))),
...configFileDependencies.map((c) => new URL(c, root)),
Expand All @@ -113,6 +106,51 @@ function astroDBIntegration(): AstroIntegration {
server.restart();
}
});
// Wait for dev server log before showing "connected".
setTimeout(() => {
logger.info(
connectToStudio ? 'Connected to remote database.' : 'New local database created.'
);
if (connectToStudio) return;

const localSeedPaths = SEED_DEV_FILE_NAME.map(
(name) => new URL(name, getDbDirectoryUrl(root))
);
let seedInFlight = false;
// Load seed file on dev server startup.
if (seedFiles.get().length || localSeedPaths.find((path) => existsSync(path))) {
loadSeedModule();
}
const eagerReloadIntegrationSeedPaths = seedFiles
.get()
// Map integration seed paths to URLs, if possible.
// Module paths like `@example/seed` will be ignored
// from eager reloading.
.map((s) => (typeof s === 'string' && s.startsWith('.') ? new URL(s, root) : s))
.filter((s): s is URL => s instanceof URL);
Comment on lines +129 to +130
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: you should flip them :)

Copy link
Contributor Author

@bholmesdev bholmesdev Apr 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I see where you're coming from but we actually cannot flip these. The map() is used to convert relative path strings to URLs, then the filter() consolidates to all URL objects. If we put the filter() first, those relative path strings would get filtered out before they were converted

const eagerReloadSeedPaths = [...eagerReloadIntegrationSeedPaths, ...localSeedPaths];
server.watcher.on('all', (event, relativeEntry) => {
if (event === 'unlink' || event === 'unlinkDir') return;
// When a seed file changes, load manually
// to track when seeding finishes and log a message.
const entry = new URL(relativeEntry, root);
if (eagerReloadSeedPaths.find((path) => entry.href === path.href)) {
loadSeedModule();
}
});

function loadSeedModule() {
if (seedInFlight) return;

seedInFlight = true;
const mod = server.moduleGraph.getModuleById(resolved.seedVirtual);
if (mod) server.moduleGraph.invalidateModule(mod);
server.ssrLoadModule(resolved.seedVirtual).then(() => {
seedInFlight = false;
logger.info('Seeded database.');
});
}
}, 100);
},
'astro:build:start': async ({ logger }) => {
if (
Expand Down
2 changes: 1 addition & 1 deletion packages/db/src/core/integration/vite-plugin-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { type VitePlugin, getDbDirectoryUrl, getRemoteDatabaseUrl } from '../uti

const WITH_SEED_VIRTUAL_MODULE_ID = 'astro:db:seed';

const resolved = {
export const resolved = {
virtual: '\0' + VIRTUAL_MODULE_ID,
seedVirtual: '\0' + WITH_SEED_VIRTUAL_MODULE_ID,
};
Expand Down
Loading