3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nuxt.jsでaxiosをpluginでラッピングしてApiクライアントを作成する(Typescript)

Last updated at Posted at 2021-05-17

いちいちthis.$axios.getとか書いてるのいけてないので、axiosをラッピングするようなAPIクライアントを作りたいと思います。

以下のページを参考にTypescriptでプラグインを追加します

plugins/api-client.ts
import { Todo } from "~/types/todo";
import { Response } from "~/types/http";
import { Context, Plugin } from "@nuxt/types";
import Vue from "vue";

declare module "vue/types/vue" {
  interface Vue {
    $api: {
      getTodos: () => Promise<Response<Todo[]>>;
      addTodo: (todo: Todo) => Promise<Response<Todo>>;
      updateTodo: (todo: Todo) => Promise<Response<Todo>>;
      updatePertialTodo: (todo: Todo) => Promise<Response<Todo>>;
      deleteTodo: (todoId: number) => Promise<Response<void>>;
    };
  }
}

const BASE = "/api";
const API_TODO = `${BASE}/todos`;

const plugin: Plugin = (context: Context) => {
  Vue.prototype.$api = {
    getTodos: (): Promise<Response<Todo[]>> => context.$axios.get(API_TODO),
    addTodo: (todo: Todo): Promise<Response<Todo>> =>
      context.$axios.post(API_TODO, todo),
    updateTodo: (todo: Todo): Promise<Response<Todo>> =>
      context.$axios.put(`${API_TODO}/${todo.id}`, todo),
    updatePertialTodo: (todo: Todo): Promise<Response<Todo>> =>
      context.$axios.patch(`${API_TODO}/${todo.id}`, todo),
    deleteTodo: (todoId: number): Promise<Response<void>> =>
      context.$axios.delete(`${API_TODO}/${todoId}`)
  };
};

export default plugin;

Vue.prototype.$api = {}this.$apiが使えるようになります

types/http.d.ts
export interface Response<T> {
  status: number;
  data: T;
}
types/todo.d.ts
export interface Todo {
  id: number;
  contents: string;
  start: string;
  end: string;
  isCompleted: boolean;
}
nuxt.config.js
  plugins: [
    ・・・
    '~/plugins/api-client.ts'
  ],

これで、this.$api.getTodos()のように呼び出すことができ、いちいちaxiosをしなくて良くなります

(2021/05/20 追記)

APIがOpenAPIに対応している場合はさらにシンプルにできるので以下のページをご参照ください

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?