ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

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

2021-06-04 09:33:53  阅读:305  来源: 互联网

标签:body const mongodb CRUD response api Deno user id


启动项目监听端口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

标签:body,const,mongodb,CRUD,response,api,Deno,user,id
来源: https://www.cnblogs.com/yuanchao-blog/p/14848184.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有