0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-03-10 23:01:26 -05:00

wip: add seeding for readable collections (nonstable ids!)

This commit is contained in:
bholmesdev 2024-01-18 18:20:41 -05:00 committed by Nate Moore
parent d7b76b9638
commit af22251367

View file

@ -1,14 +1,18 @@
import type { DBCollections } from '../../types.js';
import yargs from 'yargs-parser';
import { appTokenError } from '../../errors.js';
import { getAstroStudioEnv, getStudioUrl, getRemoteDatabaseUrl, isAppTokenValid } from '../../utils.js';
import {
getAstroStudioEnv,
getStudioUrl,
getRemoteDatabaseUrl,
isAppTokenValid,
} from '../../utils.js';
import { migrate } from './migrate.js';
import { collectionToTable, createDb } from '../../internal.js';
import type { Query } from 'drizzle-orm';
import type { InArgs, InStatement } from '@libsql/client';
export async function sync({
collections,
}: {
collections: DBCollections;
}) {
export async function sync({ collections }: { collections: DBCollections }) {
const args = yargs(process.argv.slice(3), {
string: ['dry-run', 'seed'],
});
@ -27,6 +31,9 @@ export async function sync({
await setSyncStatus({ status: 'RUNNING', remoteDbUrl, appToken });
await migrate({ collections, isDryRun, appToken });
await setSyncStatus({ status: 'SUCCESS', remoteDbUrl, appToken });
if (shouldSeed) {
await tempDataPush({ collections, appToken, isDryRun });
}
// eslint-disable-next-line no-console
console.info('Sync complete 🔄');
} catch (e) {
@ -37,6 +44,46 @@ export async function sync({
}
}
/** TODO: refine with migration changes */
async function tempDataPush({
collections,
appToken,
isDryRun,
}: {
collections: DBCollections;
appToken: string;
isDryRun?: boolean;
}) {
const db = await createDb({ collections, dbUrl: ':memory:', seeding: true });
const queries: Query[] = [];
for (const [name, collection] of Object.entries(collections)) {
if (collection.writable || !collection.data) continue;
const table = collectionToTable(name, collection);
const insert = db.insert(table).values(await collection.data());
queries.push(insert.toSQL());
}
const url = new URL('/db/query', getRemoteDatabaseUrl());
const requestBody: InStatement[] = queries.map((q) => ({
sql: q.sql,
args: q.params as InArgs,
}));
if (isDryRun) {
console.info('[DRY RUN] Batch data seed:', JSON.stringify(requestBody, null, 2));
return new Response(null, { status: 200 });
}
return await fetch(url, {
method: 'POST',
headers: new Headers({
Authorization: `Bearer ${appToken}`,
}),
body: JSON.stringify(requestBody),
});
}
async function setSyncStatus({
remoteDbUrl,
appToken,