Tạo API thành access D1 bằng cách sử dụng Proxy Worker Build an API to access D1 using a proxy Worker បង្កើត API ទៅ access D1 ដោយប្រើប្រូកស៊ីកម្មករ
Hướng dẫn chi tiết đồng bộ từ docs Cloudflare — mỗi section có backlink tới đúng vị trí trên trang gốc. Detailed guide synced from Cloudflare docs — each section links to the matching anchor on the official page. មគ្គុទ្ទេសក៍លម្អិតធ្វើសមកាលពី docs Cloudflare — ផ្នែកនីមួយៗមានតំណទៅទីតាំងត្រូវគ្នានៅទំព័រផ្លូវការ។
← Danh mục ← Catalog ← បញ្ជីGiải thích nhanh Quick context បរិបទរហ័ស
Thuộc Cloudflare One — Zero Trust, truy cập an toàn và kiểm soát traffic người dùng/thiết bị. Tutorial «Xây dựng API to access D1 using proxy Worker» giúp bạn làm quen luồng triển khai thật — phù hợp đọc trước khi mở tài liệu gốc tiếng Anh. Docs gốc chia khoảng 11 bước chính; bản tóm tắt dưới đây giúp bạn nắm khung trước khi làm theo từng lệnh.
This tutorial shows how to create an API that allows you to securely run queries against a D1 database. The API can be used to customize access controls and/or limit what tables can be queried.
ការបង្រៀននេះបង្ហាញពីរបៀបបង្កើត API ដែលអនុញ្ញាតឱ្យអ្នកដំណើរការសំណួរដោយសុវត្ថិភាពប្រឆាំងនឹងមូលដ្ឋានទិន្នន័យ D1 ។ API អាចត្រូវបានប្រើដើម្បីប្ដូរតាមបំណង access គ្រប់គ្រង និង/ឬកំណត់តារាងដែលអាចសួរបាន។
Lưu ý Note ចំណាំ
Lưu ý trước khi làm Notes before you start ចំណាំមុនពេលចាប់ផ្តើម
- Đây là bản tóm tắt trên Orange Cloud Learning Hub — không thay thế tài liệu chính thức.
- Luôn mở liên kết «Tài liệu gốc» bên dưới khi cần lệnh CLI, snippet code và ảnh minh họa đầy đủ.
- Cần tài khoản Cloudflare, Wrangler CLI và (thường) hoàn thành hướng dẫn Get started của Workers/Pages.
- Zero Trust thường cần quyền admin trên tenant Cloudflare One và IdP đã kết nối.
- Docs Cloudflare cập nhật thường xuyên — đối chiếu ngày «Rà soát lần cuối» trên trang gốc khi triển khai production.
- This is a summary on Orange Cloud Learning Hub — it does not replace the official documentation.
- Open the Official docs link below for CLI commands, code snippets, and full screenshots.
- Requires a Cloudflare account, Wrangler CLI, and (typically) completing the Workers/Pages Get started guide.
- Zero Trust typically requires Cloudflare One tenant admin access and a connected IdP.
- Cloudflare docs change frequently — verify the Last reviewed date on the official page before production use.
- នេះគឺជាការសង្ខេបនៅលើ Orange Cloud Learning Hub — វាមិនជំនួសឯកសារផ្លូវការទេ។
- បើកតំណឯកសារផ្លូវការខាងក្រោមសម្រាប់ពាក្យបញ្ជា CLI កូដ snippets និងរូបថតអេក្រង់ពេញ។
- ទាមទារគណនី Cloudflare, Wrangler CLI និង (ជាធម្មតា) បំពេញការណែនាំ Workers/Pages Get started ។
- Zero Trust ជាធម្មតាទាមទារ Cloudflare One អ្នកគ្រប់គ្រងភតិកៈ access និង IdP ដែលបានតភ្ជាប់។
- Cloudflare ឯកសារផ្លាស់ប្តូរជាញឹកញាប់ — ផ្ទៀងផ្ទាត់កាលបរិច្ឆេទដែលបានពិនិត្យចុងក្រោយនៅលើទំព័រផ្លូវការមុនពេលប្រើប្រាស់ផលិតកម្ម។
Tài liệu gốc — rà soát lần cuối: over 1 year ago Official docs — last reviewed: over 1 year ago ឯកសារផ្លូវការ — ពិនិត្យចុងក្រោយ: over 1 year ago
Overview Overview ទិដ្ឋភាពទូទៅ
Trong tutorial này, bạn sẽ create an API that allows you to securely run queries against a cơ sở dữ liệu D1.
Read the "Overview" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «ទិដ្ឋភាពទូទៅ» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
Liên kết liên quan (docs Cloudflare) Related links (Cloudflare docs) តំណពាក់ព័ន្ធ (docs Cloudflare)
Điều kiện Prerequisites តម្រូវការជាមុន
Phần «Yêu cầu trước» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "Prerequisites" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «តម្រូវការជាមុន» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
- Đăng ký cho một Cloudflare account ↗.
- Cài đặt Node.js ↗
- Có một cơ sở dữ liệu hiện có D1. Nhắc đến Get started tutorial for D1
- Sign up for a Cloudflare account ↗.
- Install Node.js ↗.
- Have an existing D1 database. Refer to Get started tutorial for D1.
- ចុះឈ្មោះសម្រាប់ Cloudflare គណនី>។
- ដំឡើង Node.js ↗។
- មានមូលដ្ឋានទិន្នន័យ D1 ដែលមានស្រាប់។ សូមមើល Get started ការបង្រៀនសម្រាប់ __TERM61a_5__
16.17.0 hoặc mới hơn.16.17.0 or later.Liên kết liên quan (docs Cloudflare) Related links (Cloudflare docs) តំណពាក់ព័ន្ធ (docs Cloudflare)
1.Điều Tạo một dự án mới 1. Create a new project 1. បង្កើតគម្រោងថ្មីមួយ
Tạo new Worker to create and deploy your API.
Read the "1. Create a new project" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «1. បង្កើតគម្រោងថ្មីមួយ» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
- Tạo một Worker có tên
d1-httpbằng cách chạy:
- Create a Worker named
d1-httpby running:
- បង្កើតកម្មករម្នាក់ឈ្មោះ
d1-httpដោយដំណើរការ៖
npm create cloudflare@latest -- d1-http yarn create cloudflare d1-http pnpm create cloudflare@latest d1-http Hello World example. Đối với Mẫu nào bạn muốn sử dụng?, chọn Worker only. Đối với Ngôn ngữ nào bạn muốn sử dụng?, chọn TypeScript. Đối với Bạn muốn sử dụng git để kiểm soát phiên bản?, chọn Yes. * Đối với Bạn muốn triển khai ứng dụng của mình?, chọn No (chúng tôi sẽ thực hiện một số thay đổi trước khi triển khai).Hello World example. For Which template would you like to use?, choose Worker only. For Which language do you want to use?, choose TypeScript. For Do you want to use git for version control?, choose Yes. * For Do you want to deploy your application?, choose No (we will be making some changes before deploying).Hello World example។ សម្រាប់ តើគំរូមួយណាដែលអ្នកចង់ប្រើ? សូមជ្រើសរើស Worker only។ សម្រាប់ តើភាសាមួយណាដែលអ្នកចង់ប្រើ? សូមជ្រើសរើស TypeScript។ សម្រាប់ តើអ្នកចង់ប្រើ git សម្រាប់ការគ្រប់គ្រងកំណែទេ? សូមជ្រើសរើស Yes។ * សម្រាប់ តើអ្នកចង់ដាក់ឱ្យប្រើប្រាស់កម្មវិធីរបស់អ្នកទេ? សូមជ្រើសរើស No (យើងនឹងធ្វើការផ្លាស់ប្តូរមួយចំនួនមុនពេលដាក់ឱ្យប្រើប្រាស់)។- Thay đổi vào thư mục dự án mới của bạn để bắt đầu phát triển:
- Change into your new project directory to start developing:
- ផ្លាស់ប្តូរទៅក្នុងថតគម្រោងថ្មីរបស់អ្នក ដើម្បីចាប់ផ្តើមអភិវឌ្ឍ៖
cd d1-http 2.Đối với Cài đặt HONO 2. Install Hono 2. ដំឡើង Hono
Phần «Cài đặt Hono» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "2. Install Hono" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «2. ដំឡើង Hono» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
- Để sử dụng Hono trong dự án này, hãy cài đặt nó bằng cách sử dụng
npm:
- To use Hono in this project, install it using
npm:
- ដើម្បីប្រើ Hono ក្នុងគម្រោងនេះ សូមដំឡើងវាដោយប្រើ
npm៖
npm i hono yarn add hono pnpm add hono bun add hono 3 Cái Thêm một API.KEY 3. Add an API.KEY 3. បន្ថែម API.KEY
Phần «Thêm API.KEY» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "3. Add an API.KEY" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «3. បន្ថែម API.KEY» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
- Để phát triển cục bộ, hãy tạo tệp
.dev.varstrong thư mục gốc củad1-http. - Thêm phím API vào file như sau:
- For local development, create a
.dev.varsfile in the root directory ofd1-http. - Add your API key in the file as follows.
- សម្រាប់ការអភិវឌ្ឍន៍មូលដ្ឋាន បង្កើតឯកសារ
.dev.varsនៅក្នុងថត root នៃd1-http។ - បន្ថែមសោ API របស់អ្នកនៅក្នុងឯកសារដូចខាងក្រោម។
API_KEY="YOUR_API_KEY" YOUR<em>API</em>KEY bằng giá trị chuỗi hợp lệ. Bạn cũng có thể tạo giá trị này bằng cách sử dụng lệnh sau. Cửa sổ TerminalYOUR<em>API</em>KEY with a valid string value. You can also generate this value using the following command. Terminal windowYOUR<em>API</em>KEY ជាមួយនឹងតម្លៃខ្សែអក្សរត្រឹមត្រូវ។ អ្នកក៏អាចបង្កើតតម្លៃនេះដោយប្រើពាក្យបញ្ជាខាងក្រោម។ បង្អួចស្ថានីយopenssl rand -base64 32 API_KEY.API_KEY.API_KEY។Liên kết liên quan (docs Cloudflare) Related links (Cloudflare docs) តំណពាក់ព័ន្ធ (docs Cloudflare)
Bốn Initialize ứng dụng 4. Initialize the application 4. ចាប់ផ្តើមកម្មវិធី
Phần «Khởi tạo ứng dụng» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "4. Initialize the application" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «4. ចាប់ផ្តើមកម្មវិធី» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
- Bearer Auth ↗: Thêm xác thực vào API.
- Logger ↗: Cho phép theo dõi dòng chảy của yêu cầu và phản hồi.
- Pretty JSON ↗: Cho phép "JSON pretty print" cho các cơ quan phản hồi JSON.
- Bearer Auth ↗: Adds authentication to the API.
- Logger ↗: Allows monitoring the flow of requests and responses.
- Pretty JSON ↗: Enables "JSON pretty print" for JSON response bodies.
- Bearer Auth ↗៖ បន្ថែមការផ្ទៀងផ្ទាត់ទៅ API។
- អ្នកកាប់ឈើ ↗៖ អនុញ្ញាតឱ្យត្រួតពិនិត្យលំហូរនៃសំណើ និងការឆ្លើយតប។
- ស្អាត JSON ↗៖ បើកដំណើរការ "JSON pretty print" សម្រាប់តួការឆ្លើយតប JSON ។
- Thay thế nội dung của tập tin
src/index.tsbằng mã bên dưới.
- Replace the contents of the
src/index.tsfile with the code below.
- ជំនួសមាតិកានៃឯកសារ
src/index.tsដោយលេខកូដខាងក្រោម។
import { Hono } from "hono";
import { bearerAuth } from "hono/bearer-auth";
import { logger } from "hono/logger";
import { prettyJSON } from "hono/pretty-json";
type Bindings = {
API_KEY: string;
};
const app = new Hono<{ Bindings: Bindings }>();
app.use("*", prettyJSON(), logger(), async (c, next) => {
const auth = bearerAuth({ token: c.env.API_KEY });
return auth(c, next);
}); 5 Thêm API điểm cuối 5. Add API endpoints 5. បន្ថែម API ចំណុចបញ្ចប់
Phần «Thêm API endpoints» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "5. Add API endpoints" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «5. បន្ថែម API ចំណុចបញ្ចប់» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
- Thêm đoạn trích sau vào
src/index.tscủa bạn.
- Add the following snippet into your
src/index.ts.
- បន្ថែម snippet ខាងក្រោមទៅក្នុង
src/index.tsរបស់អ្នក។
// Paste this code at the end of the src/index.ts file
app.post("/api/all", async (c) => {
return c.text("/api/all endpoint");
});
app.post("/api/exec", async (c) => {
return c.text("/api/exec endpoint");
});
app.post("/api/batch", async (c) => {
return c.text("/api/batch endpoint");
});
export default app; /api/all POST /api/exec * POST /api/batch/api/all POST /api/exec * POST /api/batch/api/all POST /api/exec * POST /api/batch- Khởi động máy chủ phát triển bằng cách chạy lệnh sau:
- Start the development server by running the following command:
- ចាប់ផ្តើមម៉ាស៊ីនមេអភិវឌ្ឍន៍ដោយដំណើរការពាក្យបញ្ជាខាងក្រោម៖
npm run dev yarn run dev pnpm run dev - Để kiểm tra API tại địa phương, mở một thiết bị đầu cuối thứ hai.
- Trong terminal thứ hai, thực hiện lệnh cURL bên dưới. Thay thế
YOUR<em>API</em>KEYbằng giá trị bạn đã đặt trong tệp.dev.vars.
- To test the API locally, open a second terminal.
- In the second terminal, execute the below cURL command. Replace
YOUR<em>API</em>KEYwith the value you set in the.dev.varsfile.
- ដើម្បីសាកល្បង API ក្នុងមូលដ្ឋាន សូមបើកស្ថានីយទីពីរ។
- នៅក្នុងស្ថានីយទីពីរ ប្រតិបត្តិពាក្យបញ្ជា cURL ខាងក្រោម។ ជំនួស
YOUR<em>API</em>KEYជាមួយនឹងតម្លៃដែលអ្នកបានកំណត់ក្នុងឯកសារ.dev.vars។
curl -H "Authorization: Bearer YOUR_API_KEY" "http://localhost:8787/api/all" --data '{}' /api/all endpoint - Ngăn chặn máy chủ cục bộ chạy bằng cách nhấn
xtrong thiết bị đầu tiên.
- Stop the local server from running by pressing
xin the first terminal.
- បញ្ឈប់ម៉ាស៊ីនមេក្នុងស្រុកពីការដំណើរការដោយចុច
xនៅក្នុងស្ថានីយទីមួយ។
Sáu Tạo cơ sở dữ liệu 6. Create a database 6. បង្កើតមូលដ្ឋានទិន្នន័យ
If you do not have a cơ sở dữ liệu D1 already, you can create a new database with wrangler d1 create .
Read the "6. Create a database" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «6. បង្កើតមូលដ្ឋានទិន្នន័យ» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
wrangler d1 create.wrangler d1 create.wrangler d1 create។- Trong terminal của bạn, chạy:
- In your terminal, run:
- នៅក្នុងស្ថានីយរបស់អ្នក សូមដំណើរការ៖
npx wrangler d1 create d1-http-example ✅ Successfully created DB 'd1-http-example' in region EEUR
Created your new D1 database.
[[d1_databases]]
binding = "DB" # i.e. available in your Worker on env.DB
database_name = "d1-http-example"
database_id = "1234567890" database<em>name và database</em>id được hiển thị. Bạn sẽ sử dụng điều này để tham khảo cơ sở dữ liệu bằng cách tạo binding.database<em>name and database</em>id. You will use this to reference the database by creating a binding.Liên kết liên quan (docs Cloudflare) Related links (Cloudflare docs) តំណពាក់ព័ន្ធ (docs Cloudflare)
Bảy Thêm một ràng buộc 7. Add a binding 7. បន្ថែមការចង
Phần «Thêm binding» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "7. Add a binding" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «7. បន្ថែមការចង» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
- Từ thư mục
d1-httpcủa bạn, mở tệp Wrangler, tệp cấu hình của Wrangler. - Thêm liên kết sau vào file. Hãy chắc chắn rằng
database<em>namevàdatabase</em>idlà chính xác.
- From your
d1-httpfolder, open the Wrangler file, Wrangler's configuration file. - Add the following binding in the file. Make sure that the
database<em>nameand thedatabase</em>idare correct.
- ពីថត
d1-httpរបស់អ្នក បើកឯកសារ Wrangler ឯកសារកំណត់រចនាសម្ព័ន្ធរបស់ Wrangler។ - បន្ថែមការចងខាងក្រោមនៅក្នុងឯកសារ។ សូមប្រាកដថា
database<em>nameនិងdatabase</em>idត្រឹមត្រូវ។
{
"d1_databases": [
{
"binding": "DB", // i.e. available in your Worker on env.DB
"database_name": "d1-http-example",
"database_id": "1234567890"
}
]
} [[d1_databases]]
binding = "DB"
database_name = "d1-http-example"
database_id = "1234567890" - Trong tệp
src/index.tscủa bạn, hãy cập nhật kiểuBindingsbằng cách thêmDB: D1Database.
- In your
src/index.tsfile, update theBindingstype by addingDB: D1Database.
- នៅក្នុងឯកសារ
src/index.tsរបស់អ្នក ធ្វើបច្ចុប្បន្នភាពប្រភេទBindingsដោយបន្ថែមDB: D1Database។
type Bindings = {
DB: D1Database;
API_KEY: string;
}; Tám Tạo một bàn 8. Create a table 8. បង្កើតតារាង
Phần «Tạo table» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "8. Create a table" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «8. បង្កើតតារាង» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
- Tạo một thư mục mới có tên
schemasbên trong thư mụcd1-httpcủa bạn. - Tạo một tệp mới có tên
schema.sql, và dán câu lệnh SQL sau vào tệp.
- Create a new folder called
schemasinside yourd1-httpfolder. - Create a new file called
schema.sql, and paste the following SQL statement into the file.
- បង្កើតថតថ្មីមួយដែលមានឈ្មោះថា
schemasនៅក្នុងថតd1-httpរបស់អ្នក។ - បង្កើតឯកសារថ្មីមួយដែលមានឈ្មោះថា
schema.sqlហើយបិទភ្ជាប់សេចក្តីថ្លែងការណ៍ SQL ខាងក្រោមទៅក្នុងឯកសារ។
DROP TABLE IF EXISTS posts;
CREATE TABLE IF NOT EXISTS posts (
id integer PRIMARY KEY AUTOINCREMENT,
author text NOT NULL,
title text NOT NULL,
body text NOT NULL,
post_slug text NOT NULL
);
INSERT INTO posts (author, title, body, post_slug) VALUES ('Harshil', 'D1 HTTP API', 'Learn to create an API to query your D1 database.','d1-http-api'); posts nếu nó tồn tại, sau đó tạo một bảng mới posts với trường id, author, title, body và post_slug. Sau đó, nó sử dụng một câu lệnh INSERT để chiếm bảng.posts if it exists, then creates a new table posts with the field id, author, title, body, and post_slug. It then uses an INSERT statement to populate the table.posts ប្រសិនបើមាន នោះនឹងបង្កើតតារាង posts ជាមួយនឹងវាល id, author ial title និង body។ បន្ទាប់មកវាប្រើសេចក្តីថ្លែងការណ៍ INSERT ដើម្បីបំពេញតារាង។- Trong thiết bị đầu cuối của bạn, hãy thực hiện lệnh sau để tạo bảng này:
- In your terminal, execute the following command to create this table:
- នៅក្នុងស្ថានីយរបស់អ្នក ប្រតិបត្តិពាក្យបញ្ជាខាងក្រោមដើម្បីបង្កើតតារាងនេះ៖
npx wrangler d1 execute d1-http-example --file=./schemas/schema.sql "remote" : true trong cấu hình ràng buộc D1. Xem remote bindings documentation để biết thêm thông tin."remote" : true in the D1 binding configuration. Refer to the remote bindings documentation for more information."remote" : true នៅក្នុងការកំណត់រចនាសម្ព័ន្ធចង D1។ សូមមើល ឯកសារភ្ជាប់ពីចម្ងាយ> សម្រាប់ព័ត៌មានបន្ថែម។ Liên kết liên quan (docs Cloudflare) Related links (Cloudflare docs) តំណពាក់ព័ន្ធ (docs Cloudflare)
Chín Muốn cơ sở dữ liệu 9. Query the database 9. សាកសួរមូលដ្ឋានទិន្នន័យ
Your application can now access the cơ sở dữ liệu D1. In this step, you will update the API endpoints to query the database and return the result.
Read the "9. Query the database" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «9. សាកសួរមូលដ្ឋានទិន្នន័យ» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
- Trong tập tin
src/index.tscủa bạn, hãy cập nhật mã như sau.
- In your
src/index.tsfile, update the code as follow.
- នៅក្នុងឯកសារ
src/index.tsរបស់អ្នក ធ្វើបច្ចុប្បន្នភាពកូដដូចខាងក្រោម។
// Update the API routes
/**
* Executes the `stmt.run()` method.
* https://developers.cloudflare.com/d1/worker-api/prepared-statements/#run
*/
app.post('/api/all', async (c) => {
return c.text("/api/all endpoint");
try {
let { query, params } = await c.req.json();
let stmt = c.env.DB.prepare(query);
if (params) {
stmt = stmt.bind(params);
}
const result = await stmt.run();
return c.json(result);
} catch (err) {
return c.json({ error: `Failed to run query: ${err}` }, 500);
}
});
/**
* Executes the `db.exec()` method.
* https://developers.cloudflare.com/d1/worker-api/d1-database/#exec
*/
app.post('/api/exec', async (c) => {
return c.text("/api/exec endpoint");
try {
let { query } = await c.req.json();
let result = await c.env.DB.exec(query);
return c.json(result);
} catch (err) {
return c.json({ error: `Failed to run query: ${err}` }, 500);
}
});
/**
* Executes the `db.batch()` method.
* https://developers.cloudflare.com/d1/worker-api/d1-database/#batch
*/
app.post('/api/batch', async (c) => {
return c.text("/api/batch endpoint");
try {
let { batch } = await c.req.json();
let stmts = [];
for (let query of batch) {
let stmt = c.env.DB.prepare(query.query);
if (query.params) {
stmts.push(stmt.bind(query.params));
} else {
stmts.push(stmt);
}
}
const results = await c.env.DB.batch(stmts);
return c.json(results);
} catch (err) {
return c.json({ error: `Failed to run query: ${err}` }, 500);
}
});
... query và params. Những truy vấn và tham số này được truyền đến các hàm tương ứng để tương tác với cơ sở dữ liệu.query and params. These queries and parameters are passed to the respective functions to interact with the database.query និង params។ សំណួរ និងប៉ារ៉ាម៉ែត្រទាំងនេះត្រូវបានបញ្ជូនទៅមុខងាររៀងៗខ្លួនដើម្បីធ្វើអន្តរកម្មជាមួយមូលដ្ឋានទិន្នន័យ។- Nếu truy vấn thành công, bạn sẽ nhận được kết quả từ cơ sở dữ liệu.
- Nếu có lỗi, thông báo lỗi sẽ được trả về.
- If the query is successful, you receive the result from the database.
- If there is an error, the error message is returned.
- ប្រសិនបើសំណួរជោគជ័យ អ្នកទទួលបានលទ្ធផលពីមូលដ្ឋានទិន្នន័យ។
- បើមានកំហុស សារកំហុសត្រូវបានត្រឡប់មកវិញ។
Mười Kiểm tra API 10. Test the API 10. សាកល្បង API
Phần «Test API» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "10. Test the API" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «10. សាកល្បង API» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
- Khởi động máy chủ phát triển bằng cách thực hiện lệnh sau:
- Start the development server by executing the following command:
- ចាប់ផ្តើមម៉ាស៊ីនមេអភិវឌ្ឍន៍ដោយប្រតិបត្តិពាក្យបញ្ជាខាងក្រោម៖
npm run dev yarn run dev pnpm run dev - Trong cửa sổ Terminal mới, thực hiện các lệnh cURL sau. Hãy chắc chắn thay thế
YOUR<em>API</em>KEYbằng giá trị chính xác.
- In a new terminal window, execute the following cURL commands. Make sure to replace
YOUR<em>API</em>KEYwith the correct value.
- នៅក្នុងបង្អួចស្ថានីយថ្មី ប្រតិបត្តិពាក្យបញ្ជា cURL ខាងក្រោម។ សូមប្រាកដថាបានជំនួស
YOUR<em>API</em>KEYជាមួយនឹងតម្លៃត្រឹមត្រូវ។
curl -H "Authorization: Bearer YOUR_API_KEY" "http://localhost:8787/api/all" --data '{"query": "SELECT title FROM posts WHERE id=?", "params":1}' curl -H "Authorization: Bearer YOUR_API_KEY" "http://localhost:8787/api/batch" --data '{"batch": [ {"query": "SELECT title FROM posts WHERE id=?", "params":1},{"query": "SELECT id FROM posts"}]}' curl -H "Authorization: Bearer YOUR_API_KEY" "localhost:8787/api/exec" --data '{"query": "INSERT INTO posts (author, title, body, post_slug) VALUES ('\''Harshil'\'', '\''D1 HTTP API'\'', '\''Learn to create an API to query your D1 database.'\'','\''d1-http-api'\'')" }' Mười một Cài đặt API 11. Deploy the API 11. ដាក់ពង្រាយ API
Phần «Triển khai API» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "11. Deploy the API" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «11. ដាក់ពង្រាយ API» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
- Để sử dụng API trong sản xuất thay vì sử dụng nó cục bộ, bạn cần thêm bảng vào cơ sở dữ liệu từ xa (sản xuất). Để thêm bảng vào cơ sở dữ liệu sản xuất của bạn, hãy chạy lệnh sau:
- To use the API in production instead of using it locally, you need to add the table to your remote (production) database. To add the table to your production database, run the following command:
- ដើម្បីប្រើ API នៅក្នុងការផលិតជំនួសឱ្យការប្រើវាក្នុងមូលដ្ឋាន អ្នកត្រូវបន្ថែមតារាងទៅមូលដ្ឋានទិន្នន័យពីចម្ងាយ (ផលិតកម្ម) របស់អ្នក។ ដើម្បីបន្ថែមតារាងទៅក្នុងមូលដ្ឋានទិន្នន័យផលិតកម្មរបស់អ្នក សូមដំណើរការពាក្យបញ្ជាខាងក្រោម៖
npx wrangler d1 execute d1-http-example --file=./schemas/schema.sql --remote - Để triển khai ứng dụng vào mạng Cloudflare, hãy chạy lệnh sau:
- To deploy the application to the Cloudflare network, run the following command:
- ដើម្បីដាក់ពង្រាយកម្មវិធីទៅបណ្តាញ Cloudflare សូមដំណើរការពាក្យបញ្ជាខាងក្រោម៖
npx wrangler deploy ⛅️ wrangler 3.78.4 (update available 3.78.5)
-------------------------------------------------------
Total Upload: 53.00 KiB / gzip: 13.16 KiB
Your worker has access to the following bindings:
- D1 Databases:
- DB: d1-http-example (DATABASE_ID)
Uploaded d1-http (4.29 sec)
Deployed d1-http triggers (5.57 sec)
[DEPLOYED_APP_LINK]
Current Version ID: [BINDING_ID] DEPLOYED<em>APP</em>LINK). Làm một ghi chú về nó.DEPLOYED<em>APP</em>LINK). Make a note of it.DEPLOYED<em>APP</em>LINK)។ កំណត់ចំណាំរបស់វា។- Tạo một khóa API mới để sử dụng trong sản xuất.
- Generate a new API key to use in production.
- បង្កើតសោ API ថ្មី ដើម្បីប្រើក្នុងផលិតកម្ម។
openssl rand -base64 32 [YOUR_API_KEY] - Chạy lệnh
wrangler secret putđể thêm API vào dự án được triển khai.
- Execute the
wrangler secret putcommand to add an API to the deployed project.
- ប្រតិបត្តិពាក្យបញ្ជា
wrangler secret putដើម្បីបន្ថែម API ទៅគម្រោងដែលបានដាក់ពង្រាយ។
npx wrangler secret put API_KEY ✔ Enter a secret value: - Nhập giá trị của phím API của bạn (
YOUR<em>API</em>KEY). Khóa API của bạn bây giờ sẽ được thêm vào dự án của bạn. Sử dụng giá trị này, bạn có thể thực hiện các cuộc gọi API an toàn cho API được triển khai của bạn.
- Enter the value of your API key (
YOUR<em>API</em>KEY). Your API key will now be added to your project. Using this value you can make secure API calls to your deployed API.
- បញ្ចូលតម្លៃនៃសោ API របស់អ្នក (
YOUR<em>API</em>KEY)។ ឥឡូវនេះ សោ API របស់អ្នកនឹងត្រូវបានបញ្ចូលទៅក្នុងគម្រោងរបស់អ្នក។ ដោយប្រើតម្លៃនេះ អ្នកអាចធ្វើការហៅទូរស័ព្ទ API ទៅកាន់ API ដែលអ្នកបានដាក់ពង្រាយដោយសុវត្ថិភាព។
✔ Enter a secret value: [YOUR_API_KEY] 🌀 Creating the secret for the Worker "d1-http"
✨ Success! Uploaded secret API_KEY - Để kiểm tra nó, hãy chạy lệnh cURL sau với
YOUR<em>API</em>KEYvàDEPLOYED<em>APP</em>LINKchính xác.
- To test it, run the following cURL command with the correct
YOUR<em>API</em>KEYandDEPLOYED<em>APP</em>LINK.
- ដើម្បីសាកល្បងវា ដំណើរការពាក្យបញ្ជា cURL ខាងក្រោមជាមួយនឹង
YOUR<em>API</em>KEYនិងDEPLOYED<em>APP</em>LINK។
YOUR<em>API</em>KEY you have generated as the secret API key. You can also find your DEPLOYED<em>APP</em>LINK from the Cloudflare dashboard > Workers & Pages \> d1-http \> Settings \> Domains & Routes.YOUR<em>API</em>KEY you have generated as the secret API key. You can also find your DEPLOYED<em>APP</em>LINK from the Cloudflare dashboard > Workers & Pages \> d1-http \> Settings \> Domains & Routes.YOUR<em>API</em>KEY ដែលអ្នកបានបង្កើតជាសោសម្ងាត់ API។ អ្នកក៏អាចស្វែងរក DEPLOYED<em>APP</em>LINK របស់អ្នកពីផ្ទាំងគ្រប់គ្រង Cloudflare > Workers & Pages \> d1-http \> Settings \> Domains & Routes។curl -H "Authorization: Bearer YOUR_API_KEY" "https://DEPLOYED_APP_LINK/api/exec" --data '{"query": "SELECT 1"}' Summary Summary សង្ខេប
Phần «Tóm tắt» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "Summary" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «សង្ខេប» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
- Tạo API tương tác với cơ sở dữ liệu D1 của bạn.
- Phát triển API này thành Workers. Bạn có thể sử dụng API này trong ứng dụng bên ngoài của bạn để thực hiện truy vấn chống lại cơ sở dữ liệu D1 của bạn. Mã đầy đủ cho hướng dẫn này có thể được tìm thấy trên GitHub ↗.
- Created an API that interacts with your D1 database.
- Deployed this API to the Workers. You can use this API in your external application to execute queries against your D1 database. The full code for this tutorial can be found on GitHub ↗.
- បានបង្កើត API ដែលធ្វើអន្តរកម្មជាមួយមូលដ្ឋានទិន្នន័យ D1 របស់អ្នក។
- បានដាក់ពង្រាយ API នេះទៅ Workers ។ អ្នកអាចប្រើ API នេះនៅក្នុងកម្មវិធីខាងក្រៅរបស់អ្នក ដើម្បីដំណើរការសំណួរប្រឆាំងនឹងមូលដ្ឋានទិន្នន័យ D1 របស់អ្នក។ កូដពេញលេញសម្រាប់ការបង្រៀននេះអាចត្រូវបានរកឃើញនៅលើ GitHub>
Bước tiếp theo Next steps ជំហានបន្ទាប់
You can check out a similar implementation that uses Zod for validation in this GitHub repository ↗ . If you want to build an OpenAPI compliant API for your cơ sở dữ liệu D1, you should use the Cloudflare Workers OpenAPI 3.1 template ↗ .
Read the "Next steps" section below — open the official docs link for full screenshots and configuration tabs.
អានផ្នែក «ជំហានបន្ទាប់» ខាងក្រោម — បើកតំណ docs ផ្លូវការសម្រាប់រូបភាព និង tab កំណត់។
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/d1/","name":"D1"}},{"@type":"ListItem","position":3,"item":{"@id":"/d1/tutorials/","name":"Tutorials"}},{"@type":"ListItem","position":4,"item":{"@id":"/d1/tutorials/build-an-api-to-access-d1/","name":"Build an API to access D1 using a proxy Worker"}}]} Xem bản đầy đủ trên developers.cloudflare.com (ảnh, tab cấu hình). View the full guide on developers.cloudflare.com (images, config tabs). មើលមគ្គុទ្ទេសក៍ពេញលើ developers.cloudflare.com (រូបភាព, tab កំណត់)។
Tài liệu gốc ↗ Official docs ↗ ឯកសារផ្លូវការ ↗