Browse Source

init: first commit

kotoyuuko 2 weeks ago
parent
commit
40541a1488
11 changed files with 357 additions and 6 deletions
  1. 3 0
      .env.example
  2. 10 0
      .gitignore
  3. 6 0
      .prettierrc
  4. 10 5
      LICENSE
  5. 0 1
      README.md
  6. 52 0
      eslint.config.js
  7. 36 0
      package.json
  8. 110 0
      src/NotionData.ts
  9. 70 0
      src/OpenExchangeRates.ts
  10. 18 0
      src/index.ts
  11. 42 0
      tsconfig.json

+ 3 - 0
.env.example

@@ -0,0 +1,3 @@
+OPEN_EXCHANGE_RATES_KEY=
+NOTION_KEY=
+NOTION_DB_ID=

+ 10 - 0
.gitignore

@@ -27,4 +27,14 @@ build/Release
 # Dependency directory
 # https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
 node_modules
+package-lock.json
 
+# build
+build/
+
+# ide
+.idea/
+.vscode/
+
+# env
+.env

+ 6 - 0
.prettierrc

@@ -0,0 +1,6 @@
+{
+  "arrowParens": "avoid",
+  "semi": false,
+  "trailingComma": "es5",
+  "endOfLine": "lf"
+}

+ 10 - 5
LICENSE

@@ -1,8 +1,13 @@
-MIT License
-Copyright (c) <year> <copyright holders>
+        DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 
+                    Version 2, December 2004 
 
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ Copyright (C) 2025 kotoyuuko <kotoyuuko@gmail.com>
 
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ Everyone is permitted to copy and distribute verbatim or modified 
+ copies of this license document, and changing it is allowed as long 
+ as the name is changed. 
 
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 
+
+  0. You just DO WHAT THE FUCK YOU WANT TO.

+ 0 - 1
README.md

@@ -1,2 +1 @@
 # xrates_updater
-

+ 52 - 0
eslint.config.js

@@ -0,0 +1,52 @@
+const { defineConfig } = require("eslint/config")
+
+const tsParser = require("@typescript-eslint/parser")
+const typescriptEslint = require("@typescript-eslint/eslint-plugin")
+const globals = require("globals")
+const js = require("@eslint/js")
+
+const { FlatCompat } = require("@eslint/eslintrc")
+
+const compat = new FlatCompat({
+  baseDirectory: __dirname,
+  recommendedConfig: js.configs.recommended,
+  allConfig: js.configs.all,
+})
+
+module.exports = defineConfig([
+  {
+    languageOptions: {
+      parser: tsParser,
+
+      globals: {
+        ...globals.node,
+        ...globals.commonjs,
+      },
+    },
+
+    plugins: {
+      "@typescript-eslint": typescriptEslint,
+    },
+
+    extends: compat.extends(
+      "eslint:recommended",
+      "plugin:@typescript-eslint/eslint-recommended",
+      "plugin:@typescript-eslint/recommended"
+    ),
+
+    rules: {
+      "@typescript-eslint/no-unused-vars": [
+        "error",
+        {
+          args: "all",
+          argsIgnorePattern: "^_",
+          varsIgnorePattern: "^_assert",
+          caughtErrors: "none",
+          ignoreRestSiblings: true,
+        },
+      ],
+
+      "no-mixed-spaces-and-tabs": ["error", "smart-tabs"],
+    },
+  },
+])

+ 36 - 0
package.json

@@ -0,0 +1,36 @@
+{
+  "name": "xrates_updater",
+  "version": "1.0.0",
+  "description": "",
+  "main": "src/index.ts",
+  "scripts": {
+    "build": "tsc",
+    "prettier": "prettier --write .",
+    "lint": "prettier --check . && eslint . --ext .ts && cspell '**/*' ",
+    "prebuild": "npm run clean",
+    "clean": "rm -rf ./build"
+  },
+  "repository": {
+    "type": "git",
+    "url": "git@ssh.git.ac:kotoyuuko/xrates_updater.git"
+  },
+  "author": "kotoyuuko",
+  "license": "WTFPL",
+  "dependencies": {
+    "@notionhq/client": "^3.1.3",
+    "axios": "^1.9.0",
+    "dotenv": "^16.5.0"
+  },
+  "devDependencies": {
+    "@eslint/eslintrc": "^3.3.1",
+    "@eslint/js": "^9.27.0",
+    "@types/node": "^22.15.24",
+    "@typescript-eslint/eslint-plugin": "^8.33.0",
+    "@typescript-eslint/parser": "^8.33.0",
+    "eslint": "^9.27.0",
+    "globals": "^16.2.0",
+    "prettier": "^3.5.3",
+    "ts-node": "^10.9.2",
+    "typescript": "^5.8.3"
+  }
+}

+ 110 - 0
src/NotionData.ts

@@ -0,0 +1,110 @@
+import { isFullPage, Client as NotionClient } from "@notionhq/client"
+import { Currencies, RatesResp } from "./OpenExchangeRates"
+import {
+  PageObjectResponse,
+  QueryDatabaseResponse,
+} from "@notionhq/client/build/src/api-endpoints"
+
+interface Options {
+  notionKey: string
+  databaseId: string
+}
+
+export default class NotionData {
+  #notionKey: string
+  #databaseId: string
+
+  public constructor(options: Options) {
+    this.#notionKey = options.notionKey
+    this.#databaseId = options.databaseId
+  }
+
+  private async queryDatabasePages(
+    notion: NotionClient,
+    dbId: string
+  ): Promise<Array<PageObjectResponse>> {
+    let query: QueryDatabaseResponse
+    let startCursor: string | null = null
+    let fullResults: Array<PageObjectResponse> = []
+    do {
+      query = await notion.databases.query({
+        database_id: dbId,
+        page_size: 100,
+        start_cursor: startCursor ?? undefined,
+      })
+
+      const queryResults = query.results.filter(page => isFullPage(page))
+      startCursor = query.next_cursor
+
+      fullResults = [...fullResults, ...queryResults]
+    } while (query.next_cursor !== null)
+    return fullResults
+  }
+
+  public async syncCurrencies(currencies: Currencies) {
+    const notion = new NotionClient({ auth: this.#notionKey })
+    const pages = await this.queryDatabasePages(notion, this.#databaseId)
+    const existCurrencies = pages
+      .map(page => page.properties["Code"])
+      .filter(prop => prop?.type == "title")
+      .map(prop => prop.title[0]?.plain_text)
+    console.log("Exist Currencies", existCurrencies, existCurrencies.length)
+
+    for (const currency in currencies) {
+      if (existCurrencies.includes(currency)) {
+        continue
+      }
+
+      await notion.pages.create({
+        parent: {
+          database_id: this.#databaseId,
+        },
+        properties: {
+          Code: {
+            type: "title",
+            title: [
+              {
+                text: {
+                  content: currency,
+                },
+              },
+            ],
+          },
+          Rate: {
+            type: "number",
+            number: 1,
+          },
+        },
+      })
+    }
+  }
+
+  public async updateRates(ratesResp: RatesResp) {
+    const notion = new NotionClient({ auth: this.#notionKey })
+    const ratesMap = ratesResp.rates
+    const pages = await this.queryDatabasePages(notion, this.#databaseId)
+
+    for (const page of pages) {
+      let currencyCodeProp = page.properties["Code"]
+      let currencyCode = undefined
+      if (currencyCodeProp!.type === "title") {
+        currencyCode = currencyCodeProp.title[0]!.plain_text
+      } else {
+        continue
+      }
+
+      if (!(currencyCode! in ratesMap)) {
+        continue
+      }
+
+      await notion.pages.update({
+        page_id: page.id,
+        properties: {
+          Rate: {
+            number: ratesMap[currencyCode] as number,
+          },
+        },
+      })
+    }
+  }
+}

+ 70 - 0
src/OpenExchangeRates.ts

@@ -0,0 +1,70 @@
+import axios from "axios"
+
+interface Options {
+  baseUrl?: string
+  apiKey: string
+}
+
+export interface RatesResp {
+  updatedAt: string
+  rates: Rates
+}
+
+interface Rates {
+  [key: string]: number
+}
+
+export interface Currencies {
+  [key: string]: string
+}
+
+export default class OpenExchangeRates {
+  #prefixUrl: string
+  #apiKey: string
+
+  public constructor(options: Options) {
+    this.#prefixUrl = `${options.baseUrl ?? "https://openexchangerates.org"}/api/`
+    this.#apiKey = options.apiKey
+  }
+
+  private basicRequestParams(): object {
+    return {
+      app_id: this.#apiKey,
+      prettyprint: "false",
+      show_alternative: "false",
+      show_inactive: "false",
+    }
+  }
+
+  private async request(path: string, params?: object) {
+    let url = this.#prefixUrl + path + ".json"
+    let finalParams = { ...this.basicRequestParams(), ...params }
+    return await axios.get(url, {
+      headers: {
+        Accept: "application/json",
+      },
+      params: finalParams,
+    })
+  }
+
+  public async usage() {
+    const resp = await this.request("usage")
+    return resp.data
+  }
+
+  public async currencies(): Promise<Currencies> {
+    const resp = await this.request("currencies")
+    return resp.data
+  }
+
+  public async latest(currencies: Array<string>): Promise<RatesResp> {
+    const resp = await this.request("latest", {
+      base: "USD",
+      symbols: currencies.join(","),
+    })
+    return {
+      updatedAt: new Date(resp.data["timestamp"]).toISOString(),
+      rates: resp.data["rates"],
+    }
+  }
+}

+ 18 - 0
src/index.ts

@@ -0,0 +1,18 @@
+import "dotenv/config"
+import NotionData from "./NotionData"
+import OpenExchangeRates from "./OpenExchangeRates"
+;(async () => {
+  const openExchangeRates = new OpenExchangeRates({
+    apiKey: process.env["OPEN_EXCHANGE_RATES_KEY"]!,
+  })
+  const notion = new NotionData({
+    notionKey: process.env["NOTION_KEY"]!,
+    databaseId: process.env["NOTION_DB_ID"]!,
+  })
+
+  const currenciesMap = await openExchangeRates.currencies()
+  const rates = await openExchangeRates.latest(Object.keys(currenciesMap))
+
+  await notion.syncCurrencies(currenciesMap)
+  await notion.updateRates(rates)
+})()

+ 42 - 0
tsconfig.json

@@ -0,0 +1,42 @@
+{
+  "compilerOptions": {
+    /* Visit https://aka.ms/tsconfig.json to read more about this file */
+    // Recommended Node options have been incorporated from https://github.com/tsconfig/bases/blob/master/bases/node14.json
+
+    // Node LTS Fermium (14.x) has mostly complete support for ES2019 (as reported by https://node.green/)
+    "target": "ES2019",
+    "module": "commonjs",
+    // "esModuleInterop": true,
+
+    // Overrides default in order to remove "dom" because this package shouldn't assume the presence of browser APIs
+    "lib": ["ES2019"],
+
+    // Emit location
+    "outDir": "build",
+
+    // Emit sourcemaps
+    "declarationMap": true,
+    "sourceMap": true,
+    "inlineSources": true,
+
+    // Emit type definitions
+    "declaration": true,
+
+    // Strict mode
+    "strict": true,
+
+    // Allow import package.json
+    "resolveJsonModule": true,
+
+    // Linter style rules
+    "noUnusedLocals": false, // Disabled because we use eslint for this.
+    "noUnusedParameters": true,
+    "noImplicitReturns": true,
+    "noFallthroughCasesInSwitch": true,
+    "noUncheckedIndexedAccess": true,
+    "noPropertyAccessFromIndexSignature": true,
+    "forceConsistentCasingInFileNames": true
+  },
+
+  "include": ["src/**/*", "test/**/*"]
+}