@astrojs/db 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,55 @@
1
+ import type { AstroIntegration } from 'astro';
2
+ import type { z } from 'zod';
3
+ import type { MaybeArray, booleanColumnSchema, columnSchema, columnsSchema, dateColumnSchema, dbConfigSchema, indexSchema, jsonColumnSchema, numberColumnOptsSchema, numberColumnSchema, referenceableColumnSchema, tableSchema, textColumnOptsSchema, textColumnSchema } from './schemas.js';
4
+ export type Indexes = Record<string, z.infer<typeof indexSchema>>;
5
+ export type BooleanColumn = z.infer<typeof booleanColumnSchema>;
6
+ export type BooleanColumnInput = z.input<typeof booleanColumnSchema>;
7
+ export type NumberColumn = z.infer<typeof numberColumnSchema>;
8
+ export type NumberColumnInput = z.input<typeof numberColumnSchema>;
9
+ export type TextColumn = z.infer<typeof textColumnSchema>;
10
+ export type TextColumnInput = z.input<typeof textColumnSchema>;
11
+ export type DateColumn = z.infer<typeof dateColumnSchema>;
12
+ export type DateColumnInput = z.input<typeof dateColumnSchema>;
13
+ export type JsonColumn = z.infer<typeof jsonColumnSchema>;
14
+ export type JsonColumnInput = z.input<typeof jsonColumnSchema>;
15
+ export type ColumnType = BooleanColumn['type'] | NumberColumn['type'] | TextColumn['type'] | DateColumn['type'] | JsonColumn['type'];
16
+ export type DBColumn = z.infer<typeof columnSchema>;
17
+ export type DBColumnInput = DateColumnInput | BooleanColumnInput | NumberColumnInput | TextColumnInput | JsonColumnInput;
18
+ export type DBColumns = z.infer<typeof columnsSchema>;
19
+ export type DBTable = z.infer<typeof tableSchema>;
20
+ export type DBTables = Record<string, DBTable>;
21
+ export type DBSnapshot = {
22
+ schema: Record<string, DBTable>;
23
+ version: string;
24
+ };
25
+ export type DBConfigInput = z.input<typeof dbConfigSchema>;
26
+ export type DBConfig = z.infer<typeof dbConfigSchema>;
27
+ export type ColumnsConfig = z.input<typeof tableSchema>['columns'];
28
+ export type OutputColumnsConfig = z.output<typeof tableSchema>['columns'];
29
+ export interface TableConfig<TColumns extends ColumnsConfig = ColumnsConfig> extends Pick<z.input<typeof tableSchema>, 'columns' | 'indexes' | 'foreignKeys'> {
30
+ columns: TColumns;
31
+ foreignKeys?: Array<{
32
+ columns: MaybeArray<Extract<keyof TColumns, string>>;
33
+ references: () => MaybeArray<z.input<typeof referenceableColumnSchema>>;
34
+ }>;
35
+ indexes?: Record<string, IndexConfig<TColumns>>;
36
+ deprecated?: boolean;
37
+ }
38
+ interface IndexConfig<TColumns extends ColumnsConfig> extends z.input<typeof indexSchema> {
39
+ on: MaybeArray<Extract<keyof TColumns, string>>;
40
+ }
41
+ /** @deprecated Use `TableConfig` instead */
42
+ export type ResolvedCollectionConfig<TColumns extends ColumnsConfig = ColumnsConfig> = TableConfig<TColumns>;
43
+ export type NumberColumnOpts = z.input<typeof numberColumnOptsSchema>;
44
+ export type TextColumnOpts = z.input<typeof textColumnOptsSchema>;
45
+ export type AstroDbIntegration = AstroIntegration & {
46
+ hooks: {
47
+ 'astro:db:setup'?: (options: {
48
+ extendDb: (options: {
49
+ configEntrypoint?: URL | string;
50
+ seedEntrypoint?: URL | string;
51
+ }) => void;
52
+ }) => void | Promise<void>;
53
+ };
54
+ };
55
+ export {};
@@ -0,0 +1,19 @@
1
+ import type { AstroConfig, AstroIntegration } from 'astro';
2
+ import type { AstroDbIntegration } from './types.js';
3
+ export type VitePlugin = Required<AstroConfig['vite']>['plugins'][number];
4
+ export declare function getAstroStudioEnv(envMode?: string): Record<`ASTRO_STUDIO_${string}`, string>;
5
+ export declare function getRemoteDatabaseUrl(): string;
6
+ export declare function getAstroStudioUrl(): string;
7
+ export declare function getDbDirectoryUrl(root: URL | string): URL;
8
+ export declare function defineDbIntegration(integration: AstroDbIntegration): AstroIntegration;
9
+ /**
10
+ * Small wrapper around fetch that throws an error if the response is not OK. Allows for custom error handling as well through the onNotOK callback.
11
+ */
12
+ export declare function safeFetch(url: Parameters<typeof fetch>[0], options?: Parameters<typeof fetch>[1], onNotOK?: (response: Response) => void | Promise<void>): Promise<Response>;
13
+ export type Result<T> = {
14
+ success: true;
15
+ data: T;
16
+ } | {
17
+ success: false;
18
+ data: unknown;
19
+ };
@@ -0,0 +1,148 @@
1
+ import type { ColumnsConfig, DBConfigInput, TableConfig } from '../core/types.js';
2
+ export declare const column: {
3
+ number: <T extends ({
4
+ name?: string | undefined;
5
+ label?: string | undefined;
6
+ unique?: boolean | undefined;
7
+ deprecated?: boolean | undefined;
8
+ collection?: string | undefined;
9
+ } & ({
10
+ primaryKey?: false | undefined;
11
+ optional?: boolean | undefined;
12
+ default?: number | import("drizzle-orm").SQL<any> | undefined;
13
+ } | {
14
+ primaryKey: true;
15
+ optional?: false | undefined;
16
+ default?: undefined;
17
+ })) & {
18
+ references?: (() => {
19
+ type: "number";
20
+ schema: ({
21
+ name?: string | undefined;
22
+ label?: string | undefined;
23
+ unique?: boolean | undefined;
24
+ deprecated?: boolean | undefined;
25
+ collection?: string | undefined;
26
+ } & {
27
+ primaryKey?: false | undefined;
28
+ optional?: boolean | undefined;
29
+ default?: number | import("drizzle-orm").SQL<any> | undefined;
30
+ } & any) | ({
31
+ name?: string | undefined;
32
+ label?: string | undefined;
33
+ unique?: boolean | undefined;
34
+ deprecated?: boolean | undefined;
35
+ collection?: string | undefined;
36
+ } & {
37
+ primaryKey: true;
38
+ optional?: false | undefined;
39
+ default?: undefined;
40
+ } & any);
41
+ }) | undefined;
42
+ }>(opts?: T) => {
43
+ type: "number";
44
+ /**
45
+ * @internal
46
+ */
47
+ schema: T;
48
+ };
49
+ boolean: <T_1 extends {
50
+ name?: string | undefined;
51
+ label?: string | undefined;
52
+ optional?: boolean | undefined;
53
+ unique?: boolean | undefined;
54
+ deprecated?: boolean | undefined;
55
+ collection?: string | undefined;
56
+ default?: boolean | import("drizzle-orm").SQL<any> | undefined;
57
+ }>(opts?: T_1) => {
58
+ type: "boolean";
59
+ /**
60
+ * @internal
61
+ */
62
+ schema: T_1;
63
+ };
64
+ text: <T_2 extends ({
65
+ name?: string | undefined;
66
+ label?: string | undefined;
67
+ unique?: boolean | undefined;
68
+ deprecated?: boolean | undefined;
69
+ collection?: string | undefined;
70
+ default?: string | import("drizzle-orm").SQL<any> | undefined;
71
+ multiline?: boolean | undefined;
72
+ } & ({
73
+ primaryKey?: false | undefined;
74
+ optional?: boolean | undefined;
75
+ } | {
76
+ primaryKey: true;
77
+ optional?: false | undefined;
78
+ })) & {
79
+ references?: (() => {
80
+ type: "text";
81
+ schema: ({
82
+ name?: string | undefined;
83
+ label?: string | undefined;
84
+ unique?: boolean | undefined;
85
+ deprecated?: boolean | undefined;
86
+ collection?: string | undefined;
87
+ default?: string | import("drizzle-orm").SQL<any> | undefined;
88
+ multiline?: boolean | undefined;
89
+ } & {
90
+ primaryKey?: false | undefined;
91
+ optional?: boolean | undefined;
92
+ } & any) | ({
93
+ name?: string | undefined;
94
+ label?: string | undefined;
95
+ unique?: boolean | undefined;
96
+ deprecated?: boolean | undefined;
97
+ collection?: string | undefined;
98
+ default?: string | import("drizzle-orm").SQL<any> | undefined;
99
+ multiline?: boolean | undefined;
100
+ } & {
101
+ primaryKey: true;
102
+ optional?: false | undefined;
103
+ } & any);
104
+ }) | undefined;
105
+ }>(opts?: T_2) => {
106
+ type: "text";
107
+ /**
108
+ * @internal
109
+ */
110
+ schema: T_2;
111
+ };
112
+ date<T_3 extends {
113
+ name?: string | undefined;
114
+ label?: string | undefined;
115
+ optional?: boolean | undefined;
116
+ unique?: boolean | undefined;
117
+ deprecated?: boolean | undefined;
118
+ collection?: string | undefined;
119
+ default?: Date | import("drizzle-orm").SQL<any> | undefined;
120
+ }>(opts?: T_3): {
121
+ type: "date";
122
+ /**
123
+ * @internal
124
+ */
125
+ schema: T_3;
126
+ };
127
+ json<T_4 extends {
128
+ name?: string | undefined;
129
+ label?: string | undefined;
130
+ optional?: boolean | undefined;
131
+ unique?: boolean | undefined;
132
+ deprecated?: boolean | undefined;
133
+ collection?: string | undefined;
134
+ default?: unknown;
135
+ }>(opts?: T_4): {
136
+ type: "json";
137
+ /**
138
+ * @internal
139
+ */
140
+ schema: T_4;
141
+ };
142
+ };
143
+ export declare function defineTable<TColumns extends ColumnsConfig>(userConfig: TableConfig<TColumns>): TableConfig<TColumns>;
144
+ export declare function defineDb(userConfig: DBConfigInput): {
145
+ tables?: unknown;
146
+ };
147
+ export { NOW, TRUE, FALSE } from './index.js';
148
+ export { sql, eq, gt, gte, lt, lte, ne, isNull, isNotNull, inArray, notInArray, exists, notExists, between, notBetween, like, notIlike, not, asc, desc, and, or, } from 'drizzle-orm';
@@ -0,0 +1,5 @@
1
+ import type { LibSQLDatabase } from 'drizzle-orm/libsql';
2
+ export declare function createLocalDatabaseClient({ dbUrl }: {
3
+ dbUrl: string;
4
+ }): LibSQLDatabase;
5
+ export declare function createRemoteDatabaseClient(appToken: string, remoteDbURL: string): import("drizzle-orm/sqlite-proxy").SqliteRemoteDatabase<Record<string, never>>;
@@ -0,0 +1,31 @@
1
+ import { type ColumnDataType, sql } from 'drizzle-orm';
2
+ import type { LibSQLDatabase } from 'drizzle-orm/libsql';
3
+ import { type DBColumn, type DBTable } from '../core/types.js';
4
+ export { sql };
5
+ export type SqliteDB = LibSQLDatabase;
6
+ export type { Table } from './types.js';
7
+ export { createRemoteDatabaseClient, createLocalDatabaseClient } from './db-client.js';
8
+ export { seedLocal } from './seed-local.js';
9
+ export declare function hasPrimaryKey(column: DBColumn): boolean;
10
+ export declare const NOW: import("drizzle-orm").SQL<unknown>;
11
+ export declare const TRUE: import("drizzle-orm").SQL<unknown>;
12
+ export declare const FALSE: import("drizzle-orm").SQL<unknown>;
13
+ export declare function asDrizzleTable(name: string, table: DBTable): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
14
+ name: string;
15
+ schema: undefined;
16
+ columns: {
17
+ [x: string]: import("drizzle-orm/sqlite-core").SQLiteColumn<{
18
+ name: string;
19
+ tableName: string;
20
+ dataType: ColumnDataType;
21
+ columnType: string;
22
+ data: unknown;
23
+ driverParam: unknown;
24
+ notNull: false;
25
+ hasDefault: false;
26
+ enumValues: string[] | undefined;
27
+ baseColumn: never;
28
+ }, object>;
29
+ };
30
+ dialect: "sqlite";
31
+ }>;
@@ -0,0 +1,71 @@
1
+ import type { BooleanColumn, ColumnType, DBColumn, DBTable, DateColumn, JsonColumn, NumberColumn, TextColumn } from '../core/types.js';
2
+ export declare const SEED_DEV_FILE_NAME: string[];
3
+ export declare function getDropTableIfExistsQuery(tableName: string): string;
4
+ export declare function getCreateTableQuery(tableName: string, table: DBTable): string;
5
+ export declare function getCreateIndexQueries(tableName: string, table: Pick<DBTable, 'indexes'>): string[];
6
+ export declare function getCreateForeignKeyQueries(tableName: string, table: DBTable): string[];
7
+ export declare function schemaTypeToSqlType(type: ColumnType): 'text' | 'integer';
8
+ export declare function getModifiers(columnName: string, column: DBColumn): string;
9
+ export declare function getReferencesConfig(column: DBColumn): {
10
+ type: "number";
11
+ schema: ({
12
+ unique: boolean;
13
+ deprecated: boolean;
14
+ name?: string | undefined;
15
+ label?: string | undefined;
16
+ collection?: string | undefined;
17
+ } & {
18
+ optional: boolean;
19
+ primaryKey: false;
20
+ default?: number | import("./types.js").SerializedSQL | undefined;
21
+ } & {
22
+ references?: any | undefined;
23
+ }) | ({
24
+ unique: boolean;
25
+ deprecated: boolean;
26
+ name?: string | undefined;
27
+ label?: string | undefined;
28
+ collection?: string | undefined;
29
+ } & {
30
+ primaryKey: true;
31
+ optional?: false | undefined;
32
+ default?: undefined;
33
+ } & {
34
+ references?: any | undefined;
35
+ });
36
+ } | {
37
+ type: "text";
38
+ schema: ({
39
+ unique: boolean;
40
+ deprecated: boolean;
41
+ name?: string | undefined;
42
+ label?: string | undefined;
43
+ collection?: string | undefined;
44
+ default?: string | import("./types.js").SerializedSQL | undefined;
45
+ multiline?: boolean | undefined;
46
+ } & {
47
+ optional: boolean;
48
+ primaryKey: false;
49
+ } & {
50
+ references?: any | undefined;
51
+ }) | ({
52
+ unique: boolean;
53
+ deprecated: boolean;
54
+ name?: string | undefined;
55
+ label?: string | undefined;
56
+ collection?: string | undefined;
57
+ default?: string | import("./types.js").SerializedSQL | undefined;
58
+ multiline?: boolean | undefined;
59
+ } & {
60
+ primaryKey: true;
61
+ optional?: false | undefined;
62
+ } & {
63
+ references?: any | undefined;
64
+ });
65
+ } | undefined;
66
+ type WithDefaultDefined<T extends DBColumn> = T & {
67
+ schema: Required<Pick<T['schema'], 'default'>>;
68
+ };
69
+ type DBColumnWithDefault = WithDefaultDefined<TextColumn> | WithDefaultDefined<DateColumn> | WithDefaultDefined<NumberColumn> | WithDefaultDefined<BooleanColumn> | WithDefaultDefined<JsonColumn>;
70
+ export declare function hasDefault(column: DBColumn): column is DBColumnWithDefault;
71
+ export {};
@@ -0,0 +1,10 @@
1
+ import type { LibSQLDatabase } from 'drizzle-orm/libsql';
2
+ import { type DBTables } from '../core/types.js';
3
+ export declare function seedLocal({ db, tables, userSeedGlob, integrationSeedFunctions, }: {
4
+ db: LibSQLDatabase;
5
+ tables: DBTables;
6
+ userSeedGlob: Record<string, {
7
+ default?: () => Promise<void>;
8
+ }>;
9
+ integrationSeedFunctions: Array<() => Promise<void>>;
10
+ }): Promise<void>;
@@ -0,0 +1,69 @@
1
+ import type { ColumnBaseConfig, ColumnDataType } from 'drizzle-orm';
2
+ import type { SQLiteColumn, SQLiteTableWithColumns } from 'drizzle-orm/sqlite-core';
3
+ import type { ColumnsConfig, DBColumn, OutputColumnsConfig } from '../core/types.js';
4
+ type GeneratedConfig<T extends ColumnDataType = ColumnDataType> = Pick<ColumnBaseConfig<T, string>, 'name' | 'tableName' | 'notNull' | 'hasDefault'>;
5
+ export type AstroText<T extends GeneratedConfig<'string'>> = SQLiteColumn<T & {
6
+ data: string;
7
+ dataType: 'string';
8
+ columnType: 'SQLiteText';
9
+ driverParam: string;
10
+ enumValues: never;
11
+ baseColumn: never;
12
+ }>;
13
+ export type AstroDate<T extends GeneratedConfig<'custom'>> = SQLiteColumn<T & {
14
+ data: Date;
15
+ dataType: 'custom';
16
+ columnType: 'SQLiteCustomColumn';
17
+ driverParam: string;
18
+ enumValues: never;
19
+ baseColumn: never;
20
+ }>;
21
+ export type AstroBoolean<T extends GeneratedConfig<'boolean'>> = SQLiteColumn<T & {
22
+ data: boolean;
23
+ dataType: 'boolean';
24
+ columnType: 'SQLiteBoolean';
25
+ driverParam: number;
26
+ enumValues: never;
27
+ baseColumn: never;
28
+ }>;
29
+ export type AstroNumber<T extends GeneratedConfig<'number'>> = SQLiteColumn<T & {
30
+ data: number;
31
+ dataType: 'number';
32
+ columnType: 'SQLiteInteger';
33
+ driverParam: number;
34
+ enumValues: never;
35
+ baseColumn: never;
36
+ }>;
37
+ export type AstroJson<T extends GeneratedConfig<'custom'>> = SQLiteColumn<T & {
38
+ data: unknown;
39
+ dataType: 'custom';
40
+ columnType: 'SQLiteCustomColumn';
41
+ driverParam: string;
42
+ enumValues: never;
43
+ baseColumn: never;
44
+ }>;
45
+ export type Column<T extends DBColumn['type'], S extends GeneratedConfig> = T extends 'boolean' ? AstroBoolean<S> : T extends 'number' ? AstroNumber<S> : T extends 'text' ? AstroText<S> : T extends 'date' ? AstroDate<S> : T extends 'json' ? AstroJson<S> : never;
46
+ export type Table<TTableName extends string, TColumns extends OutputColumnsConfig | ColumnsConfig> = SQLiteTableWithColumns<{
47
+ name: TTableName;
48
+ schema: undefined;
49
+ dialect: 'sqlite';
50
+ columns: {
51
+ [K in Extract<keyof TColumns, string>]: Column<TColumns[K]['type'], {
52
+ tableName: TTableName;
53
+ name: K;
54
+ hasDefault: TColumns[K]['schema'] extends {
55
+ default: NonNullable<unknown>;
56
+ } ? true : TColumns[K]['schema'] extends {
57
+ primaryKey: true;
58
+ } ? true : false;
59
+ notNull: TColumns[K]['schema']['optional'] extends true ? false : true;
60
+ }>;
61
+ };
62
+ }>;
63
+ export declare const SERIALIZED_SQL_KEY = "__serializedSQL";
64
+ export type SerializedSQL = {
65
+ [SERIALIZED_SQL_KEY]: true;
66
+ sql: string;
67
+ };
68
+ export declare function isSerializedSQL(value: any): value is SerializedSQL;
69
+ export {};
@@ -7,7 +7,7 @@ import ora from "ora";
7
7
  import prompts from "prompts";
8
8
  import { MISSING_SESSION_ID_ERROR } from "../../../errors.js";
9
9
  import { PROJECT_ID_FILE, getSessionIdFromFile } from "../../../tokens.js";
10
- import { getAstroStudioUrl } from "../../../utils.js";
10
+ import { getAstroStudioUrl, safeFetch } from "../../../utils.js";
11
11
  async function cmd() {
12
12
  const sessionToken = await getSessionIdFromFile();
13
13
  if (!sessionToken) {
@@ -45,30 +45,33 @@ async function linkProject(id) {
45
45
  }
46
46
  async function getWorkspaceId() {
47
47
  const linkUrl = new URL(getAstroStudioUrl() + "/api/cli/workspaces.list");
48
- const response = await fetch(linkUrl, {
49
- method: "POST",
50
- headers: {
51
- Authorization: `Bearer ${await getSessionIdFromFile()}`,
52
- "Content-Type": "application/json"
53
- }
54
- });
55
- if (!response.ok) {
56
- if (response.status === 401) {
57
- console.error(
58
- `${bgRed("Unauthorized")}
48
+ const response = await safeFetch(
49
+ linkUrl,
50
+ {
51
+ method: "POST",
52
+ headers: {
53
+ Authorization: `Bearer ${await getSessionIdFromFile()}`,
54
+ "Content-Type": "application/json"
55
+ }
56
+ },
57
+ (res) => {
58
+ if (res.status === 401) {
59
+ console.error(
60
+ `${bgRed("Unauthorized")}
59
61
 
60
62
  Are you logged in?
61
63
  Run ${cyan(
62
- "astro db login"
63
- )} to authenticate and then try linking again.
64
+ "astro db login"
65
+ )} to authenticate and then try linking again.
64
66
 
65
67
  `
66
- );
68
+ );
69
+ process.exit(1);
70
+ }
71
+ console.error(`Failed to fetch user workspace: ${res.status} ${res.statusText}`);
67
72
  process.exit(1);
68
73
  }
69
- console.error(`Failed to fetch user workspace: ${response.status} ${response.statusText}`);
70
- process.exit(1);
71
- }
74
+ );
72
75
  const { data, success } = await response.json();
73
76
  if (!success) {
74
77
  console.error(`Failed to fetch user's workspace.`);
@@ -82,31 +85,34 @@ async function createNewProject({
82
85
  region
83
86
  }) {
84
87
  const linkUrl = new URL(getAstroStudioUrl() + "/api/cli/projects.create");
85
- const response = await fetch(linkUrl, {
86
- method: "POST",
87
- headers: {
88
- Authorization: `Bearer ${await getSessionIdFromFile()}`,
89
- "Content-Type": "application/json"
88
+ const response = await safeFetch(
89
+ linkUrl,
90
+ {
91
+ method: "POST",
92
+ headers: {
93
+ Authorization: `Bearer ${await getSessionIdFromFile()}`,
94
+ "Content-Type": "application/json"
95
+ },
96
+ body: JSON.stringify({ workspaceId, name, region })
90
97
  },
91
- body: JSON.stringify({ workspaceId, name, region })
92
- });
93
- if (!response.ok) {
94
- if (response.status === 401) {
95
- console.error(
96
- `${bgRed("Unauthorized")}
98
+ (res) => {
99
+ if (res.status === 401) {
100
+ console.error(
101
+ `${bgRed("Unauthorized")}
97
102
 
98
103
  Are you logged in?
99
104
  Run ${cyan(
100
- "astro db login"
101
- )} to authenticate and then try linking again.
105
+ "astro db login"
106
+ )} to authenticate and then try linking again.
102
107
 
103
108
  `
104
- );
109
+ );
110
+ process.exit(1);
111
+ }
112
+ console.error(`Failed to create project: ${res.status} ${res.statusText}`);
105
113
  process.exit(1);
106
114
  }
107
- console.error(`Failed to create project: ${response.status} ${response.statusText}`);
108
- process.exit(1);
109
- }
115
+ );
110
116
  const { data, success } = await response.json();
111
117
  if (!success) {
112
118
  console.error(`Failed to create project.`);
@@ -116,31 +122,34 @@ async function createNewProject({
116
122
  }
117
123
  async function promptExistingProjectName({ workspaceId }) {
118
124
  const linkUrl = new URL(getAstroStudioUrl() + "/api/cli/projects.list");
119
- const response = await fetch(linkUrl, {
120
- method: "POST",
121
- headers: {
122
- Authorization: `Bearer ${await getSessionIdFromFile()}`,
123
- "Content-Type": "application/json"
125
+ const response = await safeFetch(
126
+ linkUrl,
127
+ {
128
+ method: "POST",
129
+ headers: {
130
+ Authorization: `Bearer ${await getSessionIdFromFile()}`,
131
+ "Content-Type": "application/json"
132
+ },
133
+ body: JSON.stringify({ workspaceId })
124
134
  },
125
- body: JSON.stringify({ workspaceId })
126
- });
127
- if (!response.ok) {
128
- if (response.status === 401) {
129
- console.error(
130
- `${bgRed("Unauthorized")}
135
+ (res) => {
136
+ if (res.status === 401) {
137
+ console.error(
138
+ `${bgRed("Unauthorized")}
131
139
 
132
140
  Are you logged in?
133
141
  Run ${cyan(
134
- "astro db login"
135
- )} to authenticate and then try linking again.
142
+ "astro db login"
143
+ )} to authenticate and then try linking again.
136
144
 
137
145
  `
138
- );
146
+ );
147
+ process.exit(1);
148
+ }
149
+ console.error(`Failed to fetch projects: ${res.status} ${res.statusText}`);
139
150
  process.exit(1);
140
151
  }
141
- console.error(`Failed to fetch projects: ${response.status} ${response.statusText}`);
142
- process.exit(1);
143
- }
152
+ );
144
153
  const { data, success } = await response.json();
145
154
  if (!success) {
146
155
  console.error(`Failed to fetch projects.`);
@@ -1,7 +1,7 @@
1
1
  import { MIGRATION_VERSION } from "../../../consts.js";
2
2
  import { getManagedAppTokenOrExit } from "../../../tokens.js";
3
3
  import {} from "../../../types.js";
4
- import { getRemoteDatabaseUrl } from "../../../utils.js";
4
+ import { getRemoteDatabaseUrl, safeFetch } from "../../../utils.js";
5
5
  import {
6
6
  createCurrentSnapshot,
7
7
  createEmptySnapshot,
@@ -64,18 +64,21 @@ async function pushSchema({
64
64
  return new Response(null, { status: 200 });
65
65
  }
66
66
  const url = new URL("/db/push", getRemoteDatabaseUrl());
67
- const response = await fetch(url, {
68
- method: "POST",
69
- headers: new Headers({
70
- Authorization: `Bearer ${appToken}`
71
- }),
72
- body: JSON.stringify(requestBody)
73
- });
74
- if (!response.ok) {
75
- console.error(`${url.toString()} failed: ${response.status} ${response.statusText}`);
76
- console.error(await response.text());
77
- throw new Error(`/db/push fetch failed: ${response.status} ${response.statusText}`);
78
- }
67
+ const response = await safeFetch(
68
+ url,
69
+ {
70
+ method: "POST",
71
+ headers: new Headers({
72
+ Authorization: `Bearer ${appToken}`
73
+ }),
74
+ body: JSON.stringify(requestBody)
75
+ },
76
+ async (res) => {
77
+ console.error(`${url.toString()} failed: ${res.status} ${res.statusText}`);
78
+ console.error(await res.text());
79
+ throw new Error(`/db/push fetch failed: ${res.status} ${res.statusText}`);
80
+ }
81
+ );
79
82
  const result = await response.json();
80
83
  if (!result.success) {
81
84
  console.error(`${url.toString()} unsuccessful`);
@@ -19,7 +19,7 @@ import { RENAME_COLUMN_ERROR, RENAME_TABLE_ERROR } from "../errors.js";
19
19
  import { columnSchema } from "../schemas.js";
20
20
  import {
21
21
  } from "../types.js";
22
- import { getRemoteDatabaseUrl } from "../utils.js";
22
+ import { getRemoteDatabaseUrl, safeFetch } from "../utils.js";
23
23
  const sqlite = new SQLiteAsyncDialect();
24
24
  const genTempTableName = customAlphabet("abcdefghijklmnopqrstuvwxyz", 10);
25
25
  async function getMigrationQueries({
@@ -324,17 +324,20 @@ async function getProductionCurrentSnapshot({
324
324
  appToken
325
325
  }) {
326
326
  const url = new URL("/db/schema", getRemoteDatabaseUrl());
327
- const response = await fetch(url, {
328
- method: "POST",
329
- headers: new Headers({
330
- Authorization: `Bearer ${appToken}`
331
- })
332
- });
333
- if (!response.ok) {
334
- console.error(`${url.toString()} failed: ${response.status} ${response.statusText}`);
335
- console.error(await response.text());
336
- throw new Error(`/db/schema fetch failed: ${response.status} ${response.statusText}`);
337
- }
327
+ const response = await safeFetch(
328
+ url,
329
+ {
330
+ method: "POST",
331
+ headers: new Headers({
332
+ Authorization: `Bearer ${appToken}`
333
+ })
334
+ },
335
+ async (res) => {
336
+ console.error(`${url.toString()} failed: ${res.status} ${res.statusText}`);
337
+ console.error(await res.text());
338
+ throw new Error(`/db/schema fetch failed: ${res.status} ${res.statusText}`);
339
+ }
340
+ );
338
341
  const result = await response.json();
339
342
  if (!result.success) {
340
343
  console.error(`${url.toString()} unsuccessful`);