Nuxt.js で Repository を使う

repositories/PostRepository.js

const deserialize = json => {
  return {
    // 省略
  }
}

const serialize = post => {
  return {
    // 省略
  }
}

export default $axios => {
  return {
    async all() {
      const res = await $axios.get('/posts')
      return res.data.posts.map(json => deserialize(json))
    },
    async find(id) {
      const res = await $axios.get(`/posts/${id}`)
      return deserialize(res.data.post)
    },
    async create(post) {
      delete post.id
      const res = await $axios.post('/posts', { post: serialize(post) })
      return deserialize(res.data.post)
    },
    async update(post) {
      const path = `/posts/${post.id}`
      delete post.id
      const res = await $axios.put(path, { post: serialize(post) })
      return deserialize(res.data.post)
    },
    async destroy(post) {
      await $axios.delete(`/posts/${post.id}`)
    },
  }
}

plugins/repositories.js

import PostRepository from '@/repositories/PostRepository'

export default ({ $axios }, inject) => {
  const posts = PostRepository($axios)
  const repositories = { posts }
  inject('repositories', repositories)
}

nuxt.config.js

plugins: [
  '@/plugins/axios',
  '@/plugins/repositories',
],

参考