侯智晟
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Deno crash course ###### tags: `deno` `typeScript` > [TOC] [Deno](https://deno.land/) # Deno CLI ![](https://i.imgur.com/00Bs55H.png) # Deno standard library [Library source](https://deno.land/std@0.158.0?source) ``` deno run <fileName or URL> ``` ![](https://i.imgur.com/dk3MZGg.png) ![](https://i.imgur.com/faJNHJ0.png) # Install scribe http/server.ts ![](https://i.imgur.com/trnznQk.png) deno runs in the sandbox and we need to add these flags if we want certain permission. So this actually requires read permission and network permission. So, we have to run it with some flag ![](https://i.imgur.com/8CwvIYK.png) We can also install it ![](https://i.imgur.com/qFTNmrn.png) # Import Library <!-- How can we use something from the standard library --> The example of how to use standard library library module ```typescript import { dayOfYear, currentDayOfYear } from "https://deno.land/std@0.158.0/datetime/mod.ts"; console.log(dayOfYear(new Date("1992-11-11"))); ``` # File ## Create a File Our mission are creating the file called meowhecker.txt ### Create an encoder and Texts ```typescript= const encoder = new TextEncoder //utf-8 const greetText = encoder.encode("Hello \n meowhecker 大人") ``` ### Write and create it ```typescript //write file await Deno.writeFile("greet.txt", greetText) ``` Await is used to wait for the promise(only can be used in the async function ) use write file method on the deno namespace ### Run ``` deno run --allow-write .\creatFile.ts ``` ## Read the File ``` let file = await Deno.open("greet.txt") await Deno.copy(file, Deno.stdout) file.close() ``` ![](https://i.imgur.com/R1gqsbu.png) # REST API ## [Create Http Server](https://deno.land/std@0.60.0/http/mod.ts?s=serve) ```typescript import { serve } from "https://deno.land/std@0.60.0/http/server.ts"; const s = serve({ port: 8000 }); console.log("http://localhost:8000/"); for await (const req of s) { req.respond({ body: "Hello World\n" }); } ``` ## build API ### initialize app ```typescript import {Application, Router} from 'https://deno.land/x/oak/mod.ts' // initial APP const app = new Application() const port = 3000 console.log("Server running on port ${port}") await app.listen({port}) ``` ### Set up router (middleWare ``` const router = new Router() //for the middleware app.use(router.routes()) app.use(router.allowedMethods()) //Router router.get('/api/test1', ({response}:{response:any}) => { response.body ="meowhecker api" }) ``` ### Source ``` import {Application, Router} from 'https://deno.land/x/oak/mod.ts' const port = 3000 // initial APP const app = new Application() const router = new Router() //for the middleware app.use(router.routes()) app.use(router.allowedMethods()) //Router router.get('/api/test1', ({response}:{response:any}) => { response.body ="meowhecker api" }) console.log(`Server running on port ${port}`) await app.listen({port}) ``` ### Result ![](https://i.imgur.com/7juAq5v.png) ### Separate router from server.ts server.ts ```typescript import {Application} from 'https://deno.land/x/oak/mod.ts' import router from "./router.ts" const port = 3000 // initial APP const app = new Application() //for the middleware app.use(router.routes()) app.use(router.allowedMethods()) console.log(`Server running on port ${port}`) await app.listen({port}) ``` router.ts ```typescript import {Router} from 'https://deno.land/x/oak/mod.ts' const router = new Router() //Router router.get('/api/test1', ({response}:{response:any}) => { response.body ="meowhecker api" }) export default router //pass router ``` ## Controller Separate file for Route function Create controller ![](https://i.imgur.com/V06DoTI.png) ```typescript // Declare data type interface Guns{ id:string, name:string, description:string, price:number } let guns:Guns[] = [ { id:"1", name: "ak47", description:"Refle", price:2500 } , { id:"2", name: "Kar-98", description:"Sniper Refle", price:4500 } , { id:"3", name: "MP5", description:"summachine gun", price:1500 } ] ``` ### Separate the interface However, we could use export and create the file which called type.ts In this way, we could import it in anywhere. type.ts ```typescript export interface Guns{ id:number, name:string, description:string, price:number } ``` guns.ts ```typescript import {Guns} from "../type" let guns:Guns[] = [ { id:1, name: "ak47", description:"Refle", price:2500 } , { id:2, name: "Kar-98", description:"Sniper Refle", price:4500 } , { id:3, name: "MP5", description:"summachine gun", price:1500 } ] ``` ### Get all guns(Controller) controller function is going to hooked to our route ```typescript // GET Guns const getGuns = ({response}:{response:any}) =>{ response.body={ success:true, data:guns } } export {getGuns} ``` ```typescript //Router router.get('/api/Guns', getGuns) ``` ![](https://i.imgur.com/wtJFYgr.png) ### API router API Router router.ts ```typescript router.get('/api/Guns', getGuns) .get('/api/getGun/:id', getGun) .post('/api/addGun', addGun) .put('/api/updateGun/:id', updateGun) .delete('/api/deleteGun/:id', deleteGun) ``` controller (test) ```typescript //Controller function // GET Guns const getGuns = ({response}:{response:any}) =>{ response.body={ success:true, data:guns } } //Get single Gun const getGun = ({response}:{response:any}) =>{ response.body="get single" } //Add a Gun const addGun = ({response}:{response:any}) =>{ response.body="Post request" } //Update a Gun const updateGun = ({response}:{response:any}) =>{ response.body="Put resequest" } //Delete a Gun const deleteGun = ({response}:{response:any}) =>{ response.body="delete request" } export {getGuns,getGun,addGun,updateGun,deleteGun} ``` ### Get a Single gun We need to grab on to this ID that's pass in, So in addition to response we want "params" #### To get a single gun ```typescript const gun:Guns | undefined = Guns.find(g => g.id === params.id) ``` guns.find: for each gun we want to get the gun where the id equal to to the params ID ```typescript const getGun = ({response, params}:{response:any, params:{id:string}}) =>{ const gun:Guns | undefined = guns.find(p => p.id === params.id) //if gun was found if(gun){ response.status = 200 response.body = { success: true, data: gun } } else{ response.status =404, response.body = { success: false, msg: "no message found" } } } ``` ![](https://i.imgur.com/uue6cMB.png) ## Add the single Gun To get the the data that's from the client we have to pass in () here request if await has squiggly line. because this is no longer scope or top-level, we have to add a sync here There has a bug with the generate function, I didn't know how to solve it. I think probably the problem with the version is too old(v4) ```typescript const addGun = async({response, request}:{response:any, request:any}) =>{ // response.body="Post request" const body = await request.body() //body method() which returns a promis we need to use await if(!request.hasBody){ response.status=400 response.body={ success: false, msg: "No data" } }else{ const gun: Guns = body.value // the value we're going to assign to this variable(json) //create the ID, because you don't create the ID from the client, it get added by the database // gun.id=v4.generate() //so once we have the gun constructed, we'll go ahead and take the product array and push on to it, guns.push(gun) response.status= 201 //201 means everything went okay and something got create response.body ={ success: true, data: gun } } } ``` ## Update the gun ```typescript const updateGun = async({params, request, response}:{params:{id:string}, request:any, response:any}) =>{ const gun:Guns | undefined = guns.find(p => p.id === params.id) //getting the gun by params ID //if gun was found if(gun){ const body = await request.body() const updateData : {name?:string; description?:string; price?:number} =body.value // using map to updata guns = guns.map(p=> p.id === params.id ? {...p,...updateData}:p ) response.status = 200 response.body={ success:true, data: guns } } else{ response.status =404 response.body = { success: false, msg: "no message found" } } ``` ## Delete guns ![](https://i.imgur.com/D17lpLn.png) ```typescript const deleteGun = ({params,response}:{params:{id:string},response:any}) =>{ guns = guns.filter(p => p.id !== params.id) response.body = { success: true, msg:"guns removed" } } ``` # Solve Error ![](https://i.imgur.com/lvk5DWL.png) the error is header didn't carry the contain od the content-type, So now we just adding it. the problem is going to be solve. ![](https://i.imgur.com/jBU6v0P.png) # VSC extension ![](https://i.imgur.com/1AenxWN.png)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully