Edits history of script submission #23117 for ' Query D1 Database (cloudflare)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    export type DynSelect_database_id = string
    
    // Dropdown of the account's D1 databases, by name.
    export async function database_id(auth: RT.Cloudflare) {
      const response = await fetch(
        `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/d1/database?per_page=100`,
        {
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
        }
      )
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { result } = (await response.json()) as {
        result: { uuid: string; name: string }[]
      }
      return result.map((d) => ({ value: d.uuid, label: d.name }))
    }
    
    /**
     * Query D1 Database
     * Run a SQL statement against a D1 database. Use ? placeholders and pass their values in params.
     */
    export async function main(
      auth: RT.Cloudflare,
      database_id: DynSelect_database_id,
      sql: string,
      params: string[] | undefined
    ) {
      const response = await fetch(
        `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/d1/database/${database_id}/query`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${auth.token}`,
            "Content-Type": "application/json",
            Accept: "application/json",
          },
          body: JSON.stringify({ sql, params: params ?? [] }),
        }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 4 hours ago