Deno + mongodb实现增删查改(CRUD)的restful接口

启动项目监听端口Server.ts

import { Application  } from 'https://deno.land/x/oak/mod.ts';
import router from "./routes.ts"; // Bringing in router
const PORT = 3000;

const app = new Application();
app.use(router.routes()); // Pass our router as a middleware
app.use(router.allowedMethods()); // Allow HTTP methods on router

await app.listen({ port: PORT })
console.log(`Server running on PORT: ${PORT}`)

引入router并定义相应的接口和接口路径(router.ts)

import { Router } from "https://deno.land/x/oak/mod.ts";
import {
    addUser, getUserById, getUserList, updateUser, deleteUser
  } from "./controllers.ts";
const router = new Router(); // Create Router

router
  .get("/api/user", getUserList) // Get all users
  .get("/api/user/:id", getUserById) // Get one user by id
  .post("/api/user", addUser) // Add a user
  .put("/api/user/:id", updateUser) // Update a user by id
  .delete("/api/user/:id", deleteUser); // Delete a user by id

export default router;

定义mongodb集合数据字段

export interface User {
    userName: string;
    email: string;
    password: string;
    isAdmin: boolean;
  }

链接Mongodb查询操作数据

根据_id查询数据时,需要使用BSON

  • mongodb官网使用的是
{ "_id": BSON.ObjectId("5ad84b81b8b998278f773c1b") }
import { Bson } from "https://deno.land/x/bson/mod.ts";

findOne({ _id: new Bson.ObjectID(params.id) });

import { MongoClient, Bson  } from "https://deno.land/x/mongo@v0.22.0/mod.ts";
import { User } from './interface.ts'
const URI = "mongodb://127.0.0.1:27017";

// Mongo Connection Init
const client = new MongoClient();
try {
    await client.connect(URI);
    console.log("Database successfully connected");
} catch (err) {
    console.log(err);
}

const db = client.database("denoApp");
const usersCollection = db.collection<User>("userTable");


const addUser = async ({
    request,
    response,
}: {
    request: any;
    response: any;
}) => {
    try {
        // If the request has no Body, it will return a 404
        if (!request.hasBody) {
            response.status = 400;
            response.body = {
                success: false,
                msg: "No Data",
            };
        } else {
            // Otherwise, it will try to insert 
            // a user in the DB and respond with 201
            const body = await request.body();
            const userValue = await body.value;
            console.log(body);
            await usersCollection.insertOne(userValue);
            response.status = 201;
            response.body = {
                success: true,
                data: userValue,
            };
        }
    } catch (err) {
        response.body = {
            success: false,
            msg: err.toString(),
        };
    }
};

// DESC: GET single user
// METHOD: GET /api/user/:id
// mongodb _id is Symbol type in deno so getUserById can't find data
const getUserById = async ({
    params,
    response,
}: {
    params: { id: string };
    response: any;
}) => {
    // Searches for a particular user in the DB
    const findData = await usersCollection.findOne({ _id: new Bson.ObjectID(params.id) });
    console.log(params);

    console.log(findData);
    // If found, respond with the user. If not, respond with a 404
    if (findData) {
        response.status = 200;
        response.body = {
            success: true,
            data: findData,
        };
    } else {
        response.status = 404;
        response.body = {
            success: false,
            msg: "No user found",
        };
    }
};

// DESC: GET all user
// METHOD GET /api/user
const getUserList = async ({ response }: { response: any }) => {
    try {
        // Find all user and convert them into an Array
        const userList = await usersCollection.find({}).toArray();
        if (userList) {
            response.status = 200;
            response.body = {
                success: true,
                data: userList,
            };
        } else {
            response.status = 500;
            response.body = {
                success: false,
                msg: "Internal Server Error",
            };
        }
    } catch (err) {
        response.body = {
            success: false,
            msg: err.toString(),
        };
    }
};

// DESC: UPDATE single user
// METHOD: PUT /api/user/:id
const updateUser = async ({
    params,
    request,
    response,
}: {
    params: { id: string };
    request: any;
    response: any;
}) => {
    try {
        // Search a user in the DB and update with given values if found
        const body = await request.body();
        const userValue = await body.value;
        await usersCollection.updateOne(
            { _id: new Bson.ObjectID(params.id) },
            { $set: userValue }
        );
        // Respond with the Updated user
        const updatedUser = await usersCollection.findOne({ _id: new Bson.ObjectID(params.id) });
        response.status = 200;
        response.body = {
            success: true,
            data: updatedUser,
        };
    } catch (err) {
        response.body = {
            success: false,
            msg: err.toString(),
        };
    }
};

// DESC: DELETE single user
// METHOD: DELETE /api/user/:id
const deleteUser = async ({
    params,
    response,
}: {
    params: { id: string };
    request: any;
    response: any;
}) => {
    try {
        await usersCollection.delete({ _id: new Bson.ObjectID(params.id) });
        response.status = 201;
        response.body = {
            success: true,
            msg: "deleted success",
        };
    } catch (err) {
        response.body = {
            success: false,
            msg: err.toString(),
        };
    }
};

export {
    addUser, getUserById, getUserList, updateUser, deleteUser
}
``

### 启动项目

```bash
deno run --allow-all server.ts

使用接口

  • addUser
Request:
POST
url: 
http://localhost:3000/api/user/
param:
{ 
    "userName": "user11",
    "email": "2428306489@qq.com",
    "password": "password1",
    "isAdmin": false
}

  • getUserById
Request:
GET

url: 
http://localhost:3000/api/user/:id

  • getUserList
Request:
GET

url: 
http://localhost:3000/api/user/

  • updateUser
Request:
PUT

url: 
http://localhost:3000/api/user/:id

param:
{ 
    "userName": "user11",
    "email": "2428306489@qq.com",
    "password": "password1",
    "isAdmin": false
}

  • deleteUser
Request:
DELETE

url: 
http://localhost:3000/api/user/:id

  • deleteUser

https://dev.to/nakshcodes/create-your-first-restful-api-with-deno-oak-and-mongodb-48a7

上一篇:关于字符串拼接的字节码分析


下一篇:node 连接MySql数据库 实现数据的CRUD