()
| 102 | |
| 103 | // Function to create database and update wrangler.toml |
| 104 | async function createDatabaseAndConfigure() { |
| 105 | intro(`Let's set up your database...`); |
| 106 | const defaultDBName = `${path.basename(process.cwd())}-db`; |
| 107 | dbName = await prompt("Enter the name of your database", defaultDBName); |
| 108 | |
| 109 | let databaseID: string; |
| 110 | |
| 111 | const wranglerTomlPath = path.join(__dirname, "..", "wrangler.toml"); |
| 112 | let wranglerToml: toml.JsonMap; |
| 113 | |
| 114 | try { |
| 115 | const wranglerTomlContent = fs.readFileSync(wranglerTomlPath, "utf-8"); |
| 116 | wranglerToml = toml.parse(wranglerTomlContent); |
| 117 | } catch (error) { |
| 118 | console.error("\x1b[31mError reading wrangler.toml:", error, "\x1b[0m"); |
| 119 | cancel("Operation cancelled."); |
| 120 | } |
| 121 | |
| 122 | // Run command to create a new database |
| 123 | const creationOutput = executeCommand(`bunx wrangler d1 create ${dbName}`); |
| 124 | |
| 125 | if (creationOutput === undefined || typeof creationOutput !== "string") { |
| 126 | console.log( |
| 127 | "\x1b[33mDatabase creation failed, maybe you have already created a database with that name. I'll try to find the database ID for you.\x1b[0m", |
| 128 | ); |
| 129 | const dbInfoOutput = executeCommand(`bunx wrangler d1 info ${dbName}`); |
| 130 | const getInfo = (dbInfoOutput as string).match( |
| 131 | /│ [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} │/i, |
| 132 | ); |
| 133 | if (getInfo && getInfo.length === 1) { |
| 134 | console.log( |
| 135 | "\x1b[33mFound it! The database ID is: ", |
| 136 | getInfo[0], |
| 137 | "\x1b[0m", |
| 138 | ); |
| 139 | databaseID = getInfo[0].replace("│ ", "").replace(" │", ""); |
| 140 | } else { |
| 141 | console.error( |
| 142 | "\x1b[31mSomething went wrong when initialising the database. Please try again.\x1b[0m", |
| 143 | ); |
| 144 | cancel("Operation cancelled."); |
| 145 | } |
| 146 | } else { |
| 147 | // Extract database ID from the output |
| 148 | const matchResult = (creationOutput as string).match( |
| 149 | /database_id = "(.*)"/, |
| 150 | ); |
| 151 | if (matchResult && matchResult.length === 2 && matchResult !== undefined) { |
| 152 | databaseID = matchResult[1]!; |
| 153 | } else { |
| 154 | console.error("Failed to extract database ID from the output."); |
| 155 | cancel("Operation cancelled."); |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | // Update wrangler.toml with database configuration |
| 160 | wranglerToml = { |
| 161 | ...wranglerToml!, |
no test coverage detected