第七天:API Server【一】


Posted by luckstar77 on 2022-10-27

  • 寫流程文件
## 流程
- 連接 mongodb
- 建立 koa 連線
- 建立API查詢 ID 或名稱取得資料
  - 填權息成功率
  - 除權息次數
  - 填權息次數
  - 統計年分
  - 歷年平均現金殖利率
  - 歷年平均還原殖利率
  • 初始化 package.json
{
  "name": "api-stock-dividend-yield",
  "version": "1.0.0",
  "description": "提供股票的API查詢資料,例如:填權息成功率、除權息次數、填權息次數、統計年分、歷年平均現金殖利率、歷年平均還原殖利率",
  "main": "index.js",
  "scripts": {
    "test": "echo ok"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/luckstar77/api-stock-dividend-yield.git"
  },
  "keywords": [
    "TAIWAN",
    "STOCK",
    "DIVIDEND",
    "YIELD"
  ],
  "author": "Allen Lai",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/luckstar77/api-stock-dividend-yield/issues"
  },
  "homepage": "https://github.com/luckstar77/api-stock-dividend-yield#readme"
}
  • 安裝相依套件
"dependencies": {
    "express": "^4.18.1",
    "mongodb": "^4.10.0"
  },
  "devDependencies": {
    "@types/node": "^18.8.2",
    "eslint": "^8.24.0"
  }
  • 建立 express 環境
import express from "express"
const app = express()

app.get('/stock', function (req, res) {
    const { search } = req.query
  res.send('Hello World')
})

app.listen(3000)
  • 增加 eslint
{
    "editor.codeActionsOnSave": {
        "source.fixAll": true
    }
}
  • 增加 mongodb 及取得股票 API
import express from 'express';
import { connect as mongodbConnect } from './db/mongodb';

const COLLECTION = 'stock';

(async ()=> {
    const mongodbClient = await mongodbConnect();
    const app = express();

    app.get('/stock', async function (req, res) {
        const { search } = req.query;
        const stock = await mongodbClient.collection(COLLECTION).findOne({
            $or:[{id: search},{name: search}]
        });
        res.send(stock);
    });

    app.listen(3000);
})();









Related Posts

實作簡單的REST API

實作簡單的REST API

做自己的生命設計師

做自己的生命設計師

Day 66 留言板 - Part 2

Day 66 留言板 - Part 2


Comments