Kimn
    • 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
    • Make a copy
    • 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 Make a copy 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
    --- ###### tags: `TypeScript` --- # 10/23 ## 爬取網站調整 - 將爬取網站改為 [台灣水庫即時水情](https://water.taiwanstat.com/) - 原本想爬[台電系統各機組發電量](https://www.taipower.com.tw/d006/loadGraph/loadGraph/genshx_.html),但資料貌似動態產生的爬不了 ```javascript= // 字串只保留數字 const str = "123四五六" const num = str..replace(/[^\d|.]/g, ""); console.log(num); // 123 ``` - superagent 或取 html 套件 - cheerio 用 $ 解析 dom 的套件 (使用方式類似 JQ) ## Express 改良 - Decorator 不應該負責生成 router,應該另外抽離到 router.ts ```typescript= import { Router } from "express"; export default Router(); // 並修改 decorator.ts (不需要 new) ,index.ts ``` - getRequestDecorator 接收參數只能是 get post (Methods 類型),不應該是 string ```typescript= function getRequestDecorator(type: Methods){...} // 改用枚舉 export const get = getRequestDecorator(Methods.get); export const post = getRequestDecorator(Methods.post); ``` - 將 decorator 獨立成一個資料夾管理 - 再將 decorator.ts 拆成 controller、request、use,並交由 index.ts 統一匯出 - 目錄結構 ![](https://i.imgur.com/ydlbC3n.png) - CrawlerController、LoginController 中 isLogin 加入 !! ,讓 TS 判斷 isLogin 是 boolean ```typescript= // 兩次不等於 = 等於,結果一樣 const isLogin = !!(req.session ? req.session.login : false); // 封裝成一個方法 isLogin(req: BodyRequest): boolean { return !!(req.session ? req.session.login : false); } // 這樣寫會"報錯" const isLogin = this.isLogin(req); ``` :::danger 因為 LoginController 沒有被實例化,this 指向是 undefind ::: ```typescript= // 改成 static static isLogin(req: BodyRequest): boolean { return !!(req.session ? req.session.login : false); } const isLogin = LoginController.isLogin(req); ``` :::info 問題: controller.ts 中 export function controller(target: any) {...},target 是構造函數,需寫構造函數類型 ::: ```typescript= // target 是構造函數,需寫構造函數類型 (看不懂) export function controller(target: new (...args: any[]) => any) { for (let key in target.prototype) { const path: string = Reflect.getMetadata("path", target.prototype, key); const method: Methods = Reflect.getMetadata( "method", target.prototype, key ); // middleware 是 RequestHandler 需引入 const middleware: RequestHandler = Reflect.getMetadata( "middleware", target.prototype, key ); // handler 是 any 類型 先不管 const handler = target.prototype[key]; // handler 判斷去除,裝飾器寫在 handler 上,所以一定存在 if (path && method) { if (middleware) { router[method](path, middleware, handler); } else { router[method](path, handler); } } } } ``` :::info 問題: request.ts 中 target 應該是 prototype function (target: any , key: string) {...} ::: - 設置 index.ts 匯出 CrawlerController LoginController ```typescript= import { CrawlerController, LoginController } from "../controller"; function getRequestDecorator(type: Methods) { return function (path: string) { // target 指的是 prototype // 類型修改為 CrawlerController、LoginController return function (target: CrawlerController | LoginController, key: string) { Reflect.defineMetadata("path", path, target, key); Reflect.defineMetadata("method", type, target, key); }; }; } // 同樣也在 use.ts 內改寫 target 類型 ``` ```typescript= // 匯出進行共用 export enum Methods { get = "get", post = "post", } ``` :::info 需求: 二級路由,格式如下 @controller('/abc') export class CrawlerController {..} ::: ```typescript= // controller 改寫 再往外多一層 (工廠 ?) export function controller(root: string) { return function (target: new (...args: any[]) => any) { for (let key in target.prototype) { const path: string = Reflect.getMetadata("path", target.prototype, key); const method: Methods = Reflect.getMetadata( "method", target.prototype, key ); const middleware: RequestHandler = Reflect.getMetadata( "middleware", target.prototype, key ); const handler = target.prototype[key]; // path、method 必須同時存在 (自己改的) if (!path || !method) { return; } // 判斷 root 是不是 = '/' const fullPath = root === "/" ? path : `${root}${path}`; if (middleware) { router[method](path, middleware, handler); } else { router[method](fullPath, handler); } } }; } ``` :::info 需求: 多個中間件,目前只能使用一個 ::: ```typescript= @get("/showData") @use(checkLogin) @use(test) showData(req: BodyRequest, res: Response): void {...} // 修改 use.ts export function use(middleware: RequestHandler) { return function (target: CrawlerController | LoginController, key: string) { // 新增 originMiddlewares 第一次為 [],第二次先獲取再往上加 const originMiddlewares = Reflect.getMetadata("middlewares", target, key) || []; originMiddlewares.push(middleware); Reflect.defineMetadata("middlewares", originMiddlewares, target, key); ``` - 修改 controller.ts ```typescript= export function controller(root: string) { // ... // 改為 RequestHandler[] const middlewares: RequestHandler[] = Reflect.getMetadata( "middlewares", target.prototype, key ); // ... if (middlewares && middlewares.length) { // 改為 ...middlewares ( 不太懂) router[method](fullPath, ...middlewares, handler); } else { router[method](fullPath, handler); } } ``` ![](https://i.imgur.com/FtEVoKm.png) :::success 達成多個中間件都能運作的目的。 ::: ## React - 使用 React 建立前端頁面 - [Create React App](https://create-react-app.dev/docs/getting-started) > 類似 vue cli ? - `npm uninstall -g create-react-app` - 創建 react-project 使用 npm - `npx create-react-app react-project --template typescript --use-npm`

    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