In the past year, Deno and Svelte won the Breakthrough of the Year award in 2020. Deno, as a rising star project, is not very complete at present. Compared with the big guy who makes wheels when he makes a mistake, as a clown in the field of code moving brick — Copy Attacking lion can only simply record its learning process. Today I want to share how to write a simple REST API using Deno.
The target
- Familiar with Deno installation
- Familiar with Deno instructions
- Familiar with oak simple development
- Be familiar with REST Client debugging interface
Installation and configuration
For detailed installation and configuration, please refer to the official documentation: deno.land. The installation tutorial of the community can be said to be very rich. We recommend the mirror site of JustJavac: x.deno.js.cn. If you need through the website to install, address can be replaced by https://deno.land/x/install/:
Install the latest version
# # using Shell:
curl -fsSL https://x.deno.js.cn/install.sh | sh
# # using PowerShell:
iwr https://x.deno.js.cn/install.ps1 -useb | iex
Install a specific version
# # using Shell:The curl - v1.0.0 fsSL https://x.deno.js.cn/install.sh | sh - s# # using PowerShell:
$v="1.0.0"; iwr https://x.deno.js.cn/install.ps1 -useb | iex
# Verify installation
deno --version
Copy the code
If I get the output:
Deno 1.6.3 (release, x86_64-unknown-linux-GNU) V8 8.8.294 typescript 4.1.3Copy the code
deno help
Help is an amazing command that introduces a lot of key information. In Linux, the help command is built into the Shell and is used to display help information for internal Shell instructions. The help directive is also implemented in Deno. If we type Deno help or Deno –help, or even simpler deno-h, we can get a lot of information to help us get familiar with and use Deno, including introduction, document address, how to use and so on:
Root :~/deno# deno help deno 1.6.3 A secure JavaScript and TypeScript Runtime Docs: https://deno.land/manual Modules: https://deno.land/std/ https://deno.land/x/ Bugs: https://github.com/denoland/deno/issues To start the REPL: deno To execute a script: deno run https://deno.land/std/examples/welcome.ts To evaluate code in the shell: deno eval "console.log(30933 + 404)" USAGE: deno [OPTIONS] [SUBCOMMAND] OPTIONS: -h, --help Prints help information. -l, --log-level <log-level> Sets the log level. Debug, info] -q, --quiet Disable troubleshooting output --unstable Enable unstable functions and apis -v, --version Print version information SUBCOMMANDS: Bundle bundles modules and dependencies into a single file Cache Cache dependencies compile scripts into a self-contained executable file Completions generate shell auto-complete doc Displays documents for the specified module eval Eval script FMT Format the source code script help prints this help information or gives help information to the stators command info Displays information about caches or about source files e install Installs the script as an executable file Lint checks code source files LSP Start language server repL Enter interactive mode run Run the program given the module filename or URL, using "-" as the filename read from stdin. Upgrade Upgrade the denO executable to a given version of the ENVIRONMENT VARIABLES: DENO_DIR Sets the cache directory DENO_INSTALL_ROOT Sets the deno installation output directory (default: $HOME/.deno/bin) DENO_CERT loads the certificate authority NO_COLOR from the PEM encoding file to the disabled color HTTP_PROXY Proxy address of HTTP requests (downloads, FETCH module) HTTPS_PROXY Proxy address of HTTPS requests (downloads, FETCH module) NO_PROXY Host that does not use proxies. Comma-separated lists (Downloads, FETCH module)Copy the code
For more detailed instructions, please refer to @hylerrix’s CLI command to read through the full feature of Deno v1.x. I am personally interested in LSP, welcome to discuss!
JUST DO IT
It is better to travel thousands of miles than to read thousands of books. Let’s begin our exploration of Deno. Let’s start with the simplest directory:
. ├ ─ ─ mod. Ts / / entry documents ├ ─ ─ caseItem. Ts / / interface ├ ─ ─ controller. The ts / / controller ├ ─ ─ the ts / / mock data └ ─ ─ routes. The ts / / routingCopy the code
No matter what code we need to fill, let’s dig the hole and jump inside!
mkdir deno-simple-api
cd deno-simple-api
touch mod.ts
touch caseItem.ts
touch controller.ts
touch db.ts
touch routes.ts
Copy the code
In mod. Ts we use Oak to start a service:
import { Application, Router } from "https://deno.land/x/oak/mod.ts"; const app = new Application(); const router = new Router(); const port: number = 8080; router.get("/", ({ response }: { response: any }) => { response.body = { message: "Hallo Deno!" }; }); app.use(router.routes()); app.addEventListener("listen", ({ secure, hostname, port }) => { const protocol = secure ? "https://" : "http://"; const url = `${protocol}${hostname ?? "localhost"}:${port}`; console.info( `Listening on ${url}` ); }); await app.listen({ port });Copy the code
Run deno run –allow-net mod.ts and visit http://localhost:8080 to see {“message”:”Hallo deno!” }.
Among them
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
Copy the code
This line of code, Deno, imports the module through the URL and first checks to see if the module already exists locally. If not, then go to the url https://deno.land/x/oak/mod.ts, and then download the dependent package and its cache for future use. This is because Deno stores the downloaded module in the cache and uses the cache the next time it runs, which is not only faster, but can also use the module offline. When we execute deno run mod. Ts with no arguments, deno will tell us that we have no permissions:
The Download https://deno.land/x/oak/mod.ts Warning Implicitly using latest version (v6.4.1) for https://deno.land/x/oak/mod.ts Check file:///Users/gpdi/Documents/huqi/deno/deno-simple-api/mod.ts error: Uncaught PermissionDenied: The network access to "0.0.0.0:8080", run again with the --allow-net flag at processResponse (deno:core/core.js:223:11) at Object.jsonOpSync (deno:core/core.js:246:12) at opListen (deno:runtime/js/30_net.js:28:17) at Object.listen (deno:runtime/js/30_net.js:191:17) at Application.serve (server.ts:301:25) at Application.listen (application.ts:362:20) at mod.ts:22:11Copy the code
This is one of Deno’s security features: by default, access to important components of the host system, such as the network, is restricted, and you must grant Deno explicit permissions. Possible flag options are as follows:
-a, -- allow-all Allows all permissions. This will disable all security. --allow-env Allows environment access, such as getting and setting environment variables. Allow-hrtime Allows high resolution time measurement. High resolution time can be used for timed attacks and fingerprint identification. --allow-net=< url whitelist > allows network access. You can specify an optional, comma-separated list of fields to provide an allowed list of allowed fields. --allow-plugin Allows plug-ins to be loaded. Note that this is an unstable feature. --allow-read=< file whitelist > Allows file system access. You can specify an optional comma-separated list of directories or files to provide an allowed list of permitted file system access. --allow-run Allows child processes to run. Note that the subprocess is not running in a sandbox and therefore does not have the same security restrictions as the DENO process. Careful! --allow-write=< file whitelist > Allows file system write access. You can specify an optional comma-separated list of directories or files to provide an allowed list of permitted file system accessCopy the code
Next, we model caseitem.ts and write:
export default interface CaseItem {
id: string;
user_name: string;
company: string;
description: string | null;
};
Copy the code
The pseudo user model is established here, including user IDid, user name user_name, company company, and Description.
Then we simulate the next data, pretending to be from the database, and create a new DB.ts
db.ts
import CaseItem from "./caseItem.ts"; Const db: Array = [{id: "940837680722589", user_name: "rE ", company:" RE ", description: }, {id: "2330620350708823", user_name: "sh_ morning dream ", company: }, {id: "2955079655898093", user_name: "", company: "", description: "Stay Hungry, Stay Foolish.", }]; export default db;Copy the code
Then we create a controller to implement CURD and create a new controller.ts:
controller.ts
Create a route and register it:
route.ts
import { Router } from 'https://deno.land/x/oak/mod.ts';
import { getUserItems, addUserItem, getUserItem, updateUserItem, deleteUserItem } from './controller.ts';
const router = new Router();
router
.get('/users', getUserItems)
.post('/users', addUserItem)
.get('/users/:id', getUserItem)
.put('/users/:id', updateUserItem)
.delete('/users/:id', deleteUserItem);
export default router;
Copy the code
mod.ts
import { Application, Router } from "https://deno.land/x/oak/mod.ts"; import router from './routes.ts'; const app = new Application(); const port: number = 8080; app.use(router.routes()); app.use(router.allowedMethods()); app.addEventListener("listen", ({ secure, hostname, port }) => { const protocol = secure ? "https://" : "http://"; const url = `${protocol}${hostname ?? "localhost"}:${port}`; console.info( `Listening on ${url}` ); }); await app.listen({ port }); Copy the code
Next we use the REST Client to debug the CURD interface created above.
useREST Client
This is not Deno knowledge, but to make it easier for us to debug the API, the REST Client allows you to send HTTP requests and view the response directly in Visual Studio Code. Install the REST Client extension in Visual Studio Code. It is easy to install and use. To use it, simply create a file with a suffix of. HTTP or. Rest and write the code for the Request format. As shown in the following figure, just write GET http://localhost:8080 in api. HTTP and click Send Request to initiate a Request:
Then we write the above implementation of the CRUD interface debugging script, api.http:
@baseurl = http://localhost:8080 ### GET {{baseUrl}} ## GET {{baseUrl}}/users ### Add user POST {{baseUrl}}/users Content-type: application/json {"id": "1028798612771239", "user_name": "huqiu ", "company":" huqiu ", "description": GET {{baseUrl}}/users/1028798612771239 ### update user PUT {{baseUrl}}/users/1028798612771239 content-type: application/json { "description": "Copy Code, Copy World!" } ### DELETE user DELETE {{baseUrl}}/users/1028798612771239Copy the code
-
First look at all the users in db.ts:
-
Then add a new user information, return
"message": "OK"
And then I looked at all the users and found that I had been added to the user list: -
Then update my slogan, Copy Code, Copy World! , check again, update successful! :
-
Finally, I tested the delete interface, and I was completely “killed”, the user list was restored to the past calm, the big guys were still laughing, and I, it seems that I never come:
summary
Source code address: github.com/hu-qi/deno-…
Has been entangled in whether to write such a water article, hesitation, wandering, doubt, and finally write to win not to write. This is to mourn the passing years, may old age have all the memories!
Welcome to your advice!