なになれ

IT系のことを記録していきます

TypeScriptでWebAPIを実行する

TypeScriptの開発環境ができたので、とりあえずWebAPIを実行するプログラムを作ってみました。

hi1280.hatenablog.com

今回はQiitaのAPIを使いました。

https://qiita.com/api/v2/docs

使用モジュール

コード

main.ts

#!/usr/bin/env node
import axios from "axios";
import { Qiita } from "./qiita";

export async function main() {
  const res = await axios.get<Qiita[]>("https://qiita.com/api/v2/items");
  console.log(res.data);
  return res;
}

if (require.main === module) {
  main();
}

qiita.ts

// Generated by https://quicktype.io

export interface Qiita {
  rendered_body: string;
  body: string;
  coediting: boolean;
  comments_count: number;
  created_at: string;
  group: null;
  id: string;
  likes_count: number;
  private: boolean;
  reactions_count: number;
  tags: Tag[];
  title: string;
  updated_at: string;
  url: string;
  user: User;
  page_views_count: null;
}

export interface Tag {
  name: string;
  versions: any[];
}

export interface User {
  description: null | string;
  facebook_id: null | string;
  followees_count: number;
  followers_count: number;
  github_login_name: null | string;
  id: string;
  items_count: number;
  linkedin_id: null | string;
  location: null | string;
  name: string;
  organization: string | null;
  permanent_id: number;
  profile_image_url: string;
  team_only: boolean;
  twitter_screen_name: null | string;
  website_url: null | string;
}

QiitaAPIからのレスポンスデータの型はJSONからPaste JSON as CodeというVSCode拡張機能で生成しました。
JSONをコピーしてコマンドを実行するだけなので楽チンです。
Paste JSON as Code - Visual Studio Marketplace

ビルド&コマンド実行設定

TypeScriptのコードをJavaScriptにトランスパイルする

npm run build

生成したJavaScriptファイルに実行権限を与える

chmod 755 dist/*

コマンド名と実行ファイルを紐付ける

package.json ※一部省略

"bin": {
  "qiita-cli": "dist/main.js"
},

ローカルの環境でnpm packageのinstallをシミュレートする

npm link

結果

f:id:hi1280:20181205001318g:plain

参考

https://x-team.com/blog/a-guide-to-creating-a-nodejs-command/

速習 TypeScript 第2版 速習シリーズ

速習 TypeScript 第2版 速習シリーズ