跳至主要內容

連線資料庫

Deno 社群已發布許多第三方模組,讓使用者可以輕鬆連線至熱門資料庫,例如 MySQL、Postgres 和 MongoDB。

這些模組會寄存於 Deno 的第三方模組網站 deno.land/x

MySQL

deno_mysql 是 Deno 的 MySQL 和 MariaDB 資料庫驅動程式。

使用 deno_mysql 連線至 MySQL

import { Client } from "https://deno.land/x/mysql/mod.ts";

const client = await new Client().connect({
hostname: "127.0.0.1",
username: "root",
db: "dbname",
password: "password",
});

Postgres

postgresjs 是 Node.js 和 Deno 的完整 Postgres 應用程式。

使用 postgresjs 連線至 Postgres

import postgres from "https://deno.land/x/postgresjs/mod.js";

const sql = postgres("postgres://username:password@host:port/database");

MongoDB

我們建議使用 npm 規格 來使用 npm 上的官方 MongoDB 驅動程式。您可以在 官方文件 中深入了解如何使用驅動程式。在 Deno 的環境中使用此模組的唯一不同之處,在於您將使用 npm: 規格來匯入模組。

使用 npm 規格匯入 MongoDB 驅動程式
// Import the latest major version of the MongoDB driver
import { MongoClient } from "npm:mongodb@6";

// Configure a MongoDB client
const url = "mongodb://127.0.0.1:27017";
const client = new MongoClient(url);
const dbName = "myProject";

// Connect to a MongoDB instance
await client.connect();
console.log("Connected successfully to server");

// Get a reference to a collection
const db = client.db(dbName);
const collection = db.collection("documents");

// Execute an insert operation
const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }]);
console.log("Inserted documents =>", insertResult);

// Close the connection
client.close();

SQLite

在 Deno 中連接 SQLite 有兩種主要解決方案

使用 FFI 模組連接 SQLite

sqlite3 提供 JavaScript 繫結至 SQLite3 C API,使用 Deno FFI

import { Database } from "https://deno.land/x/sqlite3@LATEST_VERSION/mod.ts";

const db = new Database("test.db");

db.close();

使用經過 WASM 最佳化的模組連接 SQLite

sqlite 是適用於 JavaScript 和 TypeScript 的 SQLite 模組。此封裝器專門為 Deno 製作,並使用編譯成 WebAssembly (WASM) 的 SQLite3 版本。

import { DB } from "https://deno.land/x/sqlite/mod.ts";

const db = new DB("test.db");

db.close();

Firebase

若要使用 Deno 連接 Firebase,請使用 skypak CDN 匯入 firestore npm 模組。若要深入了解如何使用 CDN 在 Deno 中使用 npm 模組,請參閱 使用 CDN 的 npm 套件

使用 firestore npm 模組連接 Firebase

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js";

import {
addDoc,
collection,
connectFirestoreEmulator,
deleteDoc,
doc,
Firestore,
getDoc,
getDocs,
getFirestore,
query,
QuerySnapshot,
setDoc,
where,
} from "https://www.gstatic.com/firebasejs/9.8.1/firebase-firestore.js";

import { getAuth } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-auth.js";

const app = initializeApp({
apiKey: Deno.env.get("FIREBASE_API_KEY"),
authDomain: Deno.env.get("FIREBASE_AUTH_DOMAIN"),
projectId: Deno.env.get("FIREBASE_PROJECT_ID"),
storageBucket: Deno.env.get("FIREBASE_STORAGE_BUCKET"),
messagingSenderId: Deno.env.get("FIREBASE_MESSING_SENDER_ID"),
appId: Deno.env.get("FIREBASE_APP_ID"),
measurementId: Deno.env.get("FIREBASE_MEASUREMENT_ID"),
});
const db = getFirestore(app);
const auth = getAuth(app);

Supabase

若要透過 Deno 連線至 Supabase,請使用 supabase-js npm 模組 搭配 esm.sh CDN 進行匯入。若要深入瞭解如何使用 Deno 中的 npm 模組搭配 CDN,請參閱 使用 CDN 的 npm 套件

使用 supabase-js npm 模組連線至 Supabase

import { createClient } from "https://esm.sh/@supabase/supabase-js";

const options = {
schema: "public",
headers: { "x-my-custom-header": "my-app-name" },
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
};

const supabase = createClient(
"https://xyzcompany.supabase.co",
"public-anon-key",
options,
);

ORM

物件關係對映 (ORM) 將資料模型定義為可儲存在資料庫中的類別。您可以透過這些類別的執行個體讀取和寫入資料庫中的資料。

Deno 支援多個 ORM,包括 Prisma 和 DenoDB。

DenoDB

DenoDB 是 Deno 專用的 ORM。

連線至 DenoDB

import {
Database,
DataTypes,
Model,
PostgresConnector,
} from "https://deno.land/x/denodb/mod.ts";

const connection = new PostgresConnector({
host: "...",
username: "user",
password: "password",
database: "airlines",
});

const db = new Database(connection);

GraphQL

GraphQL 是一種 API 查詢語言,常被用來將不同的資料來源組合成以客戶端為中心的 API。若要設定 GraphQL API,您應該先設定 GraphQL 伺服器。此伺服器會將您的資料公開為 GraphQL API,您的客戶端應用程式可以查詢此 API 以取得資料。

伺服器

您可以使用 gql,一個適用於 Deno 的通用 GraphQL HTTP 中介軟體,在 Deno 中執行 GraphQL API 伺服器。

使用 gql 執行 GraphQL API 伺服器

import { GraphQLHTTP } from "https://deno.land/x/gql/mod.ts";
import { makeExecutableSchema } from "https://deno.land/x/graphql_tools@0.0.2/mod.ts";
import { gql } from "https://deno.land/x/graphql_tag@0.0.1/mod.ts";

const typeDefs = gql`
type Query {
hello: String
}
`;

const resolvers = {
Query: {
hello: () => `Hello World!`,
},
};

const schema = makeExecutableSchema({ resolvers, typeDefs });

Deno.serve({ port: 3000 }, async () => {
const { pathname } = new URL(req.url);

return pathname === "/graphql"
? await GraphQLHTTP<Request>({
schema,
graphiql: true,
})(req)
: new Response("Not Found", { status: 404 });
});

用戶端

若要在 Deno 中進行 GraphQL 用戶端呼叫,請使用 esm CDN 匯入 graphql npm 模組。若要深入了解如何透過 CDN 在 Deno 中使用 npm 模組,請閱讀 此處

使用 graphql npm 模組進行 GraphQL 用戶端呼叫

import { buildSchema, graphql } from "https://esm.sh/graphql";

const schema = buildSchema(`
type Query {
hello: String
}
`);

const rootValue = {
hello: () => {
return "Hello world!";
},
};

const response = await graphql({
schema,
source: "{ hello }",
rootValue,
});

console.log(response);