node deno_deno rest用于deno restful api的样板

node deno

Deno — A very young modern, and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust, and Tokio.

Deno —一个非常年轻的,现代且安全JavaScript和TypeScript运行时,使用V8,并在Rust和Tokio中构建。

I have built a quickstart boilerplate for RESTful APIs using this fantastic new technology.

我已经使用这项出色的新技术为RESTful API构建了快速入门样板。

Image for post
Deno artwork
迪诺艺术品

The full project is located at:

完整项目位于:

https://github.com/vicky-gonsalves/deno_rest

https://github.com/vicky-gonsalves/deno_rest

Let’s learn more about this project:

让我们更多地了解这个项目:

This boilerplate is based on Deno v 1.4.0

该样板基于Deno v 1.4.0

先决条件: (Pre-requisites:)

安装/升级 (Install / Upgrade)

Using Deno:

使用Deno:

deno upgrade --version 1.4.0

With Shell:

带壳:

curl -fsSL https://deno.land/x/install/install.sh | sh -s v1.4.0

With PowerShell:

使用PowerShell:

$v="1.4.0"; iwr https://deno.land/x/install/install.ps1 -useb | iex

特征 (Features)

  • Model, Controller, Service-based project structure

    模型,控制器,基于服务的项目结构
  • MongoDB

    MongoDB
  • JWT authentication

    JWT认证
  • User authorization

    用户授权
  • CORS

    CORS
  • environment management using .env

    使用.env进行环境管理
  • Request validation

    要求验证
  • Error Handling

    错误处理
  • Database seeding

    数据库播种
  • User Roles and Rights

    用户角色和权利
  • Password Encryption using AES

    使用AES的密码加密
  • Denon Integration

    天龙整合

使用的图书馆(Libraries Used)

  • Oak — A middleware framework for Deno’s net server

    Oak —用于Deno网络服务器的中间件框架

  • deno_mongo — MongoDB driver for Deno

    deno_mongoDeno的MongoDB驱动程序

  • cors — Deno.js CORS middleware

    cors — Deno.js CORS中间件

  • djwt — To make JSON Web Tokens in Deno. Based on JWT and JWS specifications.

    djwt —在Deno中制作JSON Web令牌。 基于JWT和JWS规范。

  • yup — Schema builder for value parsing and validation

    yup —用于值解析和验证的模式构建器

  • god_crypto — Encrypts passwords in AES to save in database collection.

    god_crypto —加密AES中的密码以保存在数据库集合中。

入门 (Getting Started)

Clone this repository to your local machine

将此存储库克隆到本地计算机

git clone https://github.com/vicky-gonsalves/deno_rest.git

Directory Structure

目录结构

.
├── .env/
│ ├── .env.example
│ ├── .env.development // git ignored
│ ├── .env.production // git ignored
│ └── .env.test // git ignored
├── config/
│ ├── config.ts
│ └── roles.ts
├── controllers/
│ ├── auth.controller.ts
│ └── user.controller.ts
├── data/
│ └── users.json
├── db/
│ └── db.ts
├── helpers/
│ ├── hash.helper.ts
│ └── jwt.helper.ts
├── middlewares/
│ ├── auth.middleware.ts
│ ├── errorHandler.middleware.ts
│ ├── logger.middleware.ts
│ └── validate.middleware.ts
├── models/
│ ├── token.model.ts
│ └── user.model.ts
├── routers/
│ ├── auth.router.ts
│ ├── default.router.ts
│ ├── index.ts
│ └── user.router.ts
├── services/
│ ├── auth.service.ts
│ ├── token.service.ts
│ └── user.service.ts
├── types/
│ └── types.interface.ts
├── validations/
│ ├── auth.validation.ts
│ └── user.validation.ts
├── .gitignore
├── app.ts
├── denon.json
├── deps.ts
├── lock.json
├── LICENSE
├── lock_update.sh
├── README.md
├── reload_deps.sh
├── seed.ts
└── tsconfig.json

建立 (Setup)

设定环境(Set environments)

Review .env/.env.example file and create required .env file suitable to your needs. For example: for a development environment create a file .env.development under .env directory for test environment create a file .env.test under .env directory and add necessary variables.

查看.env/.env.example文件,并创建适合您需要的所需.env文件。 例如:一个开发环境创建一个文件.env.development.env目录测试环境中创建一个文件.env.test.env目录,并添加必要的变量。

安装Deno (Install Deno)

If it's your first run, please install denon from https://deno.land/x/denon

如果是第一次运行,请从https://deno.land/x/denon安装denon

安装依赖项 (Install Dependencies)

To install dependencies, run the following command in your terminal. Note: Terminal path must be the project directory’s root path

要安装依赖项,请在终端中运行以下命令。 注意:终端路径必须是项目目录的根路径

deno cache --reload --unstable --lock-write --lock=lock.json ./deps.ts

OR run the reload_deps.sh file from the project directory

或从项目目录运行reload_deps.sh文件

This will automatically download all the dependencies and update lock.json file

这将自动下载所有依赖项并更新lock.json文件

SEED数据库(SEED Database)

If you need to seed (run migrations) database initially, Simply enable SEED=true in your .env file You can add or edit any seed file under data directory. A basic example of a seed file is provided in data/users.json

如果您需要最初为数据库设置种子(运行迁移),只需在.env文件中启用SEED=true即可在data目录下添加或编辑任何种子文件。 种子文件的基本示例在data/users.json

手动控制单个种子文件 (Manually control Individual seed file)

Logic to control seed is located in seed.ts where you can add multiple seed files as follow:

控制种子的逻辑位于seed.ts ,您可以在其中添加多个种子文件,如下所示:

const seedCollections: Array<Record<string, boolean>> = [
{ users: true }, // collection_name: boolean
{ posts: true },
{ comments: false},
...
...

Note: file name must be in collection_name.json pattern

注意:文件名必须采用collection_name.json模式

(RUN)

In your project root open terminal and run the following command to run the project

在项目根目录下打开终端并运行以下命令以运行项目

denon start

用户角色和权利 (User Roles and Rights)

User roles are saved in config/roles.ts file as:

用户角色保存在config/roles.ts文件中为:

export const roles = ["user", "admin"];

and Rights are saved as:

和“权利”另存为:

roleRights.set(roles[0], [
"getMe",
]);
roleRights.set(roles[1], [
"getMe",
"getUsers",
"manageUsers",
]);

You can add/edit roles and rights as per your requirements.

您可以根据需要添加/编辑角色和权限。

API路由 (API Routes)

All routes are stored under routers directory Below is the example of /api/users route. This route is JWT protected In user.router.ts:

所有路由都存储在routers目录下。以下是/api/users路由示例。 此路由在user.router.ts中受JWT保护:

...
/** JWT protected route */
router.post(
"/api/users", // route
auth("manageUsers"), // Auth Guard based on djwt
validate(createUserValidation), // Yup based validation
UserController.create, // Controller Function
);
...
...

Non-JWT protected route:

非JWT保护的路由:

router.post(
"/api/auth/login",
validate(loginValidation), // Yup based validation
AuthController.login,
);

楷模 (Models)

All models are under models directory example of User Model:

所有型号都在models用户模型的目录例如:

import db from "../db/db.ts";export interface UserSchema {
_id?: { $oid?: string };
name: string;
email: string;
password: string;
role: string;
isDisabled: boolean;
createdAt?: Date;
updatedAt?: Date;
}export const User = db.getDatabase.collection<UserSchema>("users");

控制器 (Controllers)

Controllers are saved under controllers directory Example of User Controller:

控制器保存在controllers目录下用户控制器示例:

...
class UserController {
/**
* Create User function * @param request
* @param response
* @returns Promise<void>
*/public static async create(
{ request, response }: RouterContext,
): Promise<void> {
const body = request.body();
let {
name,
email,
password,
role,
isDisabled,
} = await body.value;
log.debug("Creating user");
response.body = await UserService.createUser({
name,
email,
password,
role: role || roles[0],
isDisabled: typeof isDisabled === "boolean" ? isDisabled : false,
});
}
...
...

服务 (Services)

All Services are under services directory Example of User service:

所有服务都在services目录下用户服务示例:

class UserService {
/**
* Create user Service * @param options
* @returns Promise<ObjectId | Error> Returns Mongo Id of user document
*/ public static async createUser(
options: CreateUserStructure,
): Promise<ObjectId | Error> {
const { name, email, password, role, isDisabled } = options;
const hashedPassword = await HashHelper.encrypt(password);
const createdAt = new Date();
const user: ObjectId = await User.insertOne(
{ name, email, password: hashedPassword, role, isDisabled, createdAt },
);
if (!user) {
log.error("Could not create user");
return throwError({
status: Status.BadRequest,
name: "BadRequest",
path: "user",
param: "user",
message: `Could not create user`,
type: "BadRequest",
});
}
return user;
}
...
...

更新lock.json (Updating lock.json)

In your project terminal run the following command to update lock.json file with latest dependencies

在项目终端中,运行以下命令以更新具有最新依赖项的lock.json文件

deno cache --lock=lock.json --lock-write --unstable ./deps.ts

OR simply run lock_update.sh file

或只运行lock_update.sh文件

翻译自: https://medium.com/weekly-webtips/deno-rest-a-boilerplate-for-deno-restful-apis-d7ebbfed6c83

node deno

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值