Cache

2023-7-13 Less than 1 minute

http-request-mock supports the cache of data changes.

Todo:
IDTodoStatusDelete
Hit F12 to access Developer Tools and view the console logs.

# Mock data file

/**
 * @url https://some.api.com/todo
 */
const { faker, cache } = require('http-request-mock/http-request-mock.js');

const data = [...Array(5)].map(() => ({
  id: faker.incrementId(1, 'todos'),
  todo: faker.sentence(5),
  done: true,
}));

// The [data] will be memoried by localStorage.
// You can check it by localStorage.getItem('mock-todos').
const todos = cache('mock-todos', data);

module.exports = (request) => {
  if (request.query.action === 'add') {
    return add(request.query);
  }
  if (request.query.action === 'del') {
    return del(request.query);
  }
  return todos;
};

function add(query) {
  todos.push({
    id: ((todos[todos.length-1] || {}).id || 0) + 1,
    todo: query.todo,
    done: false
  });
  return { code: 0, msg: 'ok' };
}

function del(query) {
  const index = todos.findIndex(todo => todo.id === +query.id);
  todos.splice(index, 1);
  return { code: 0, msg: 'ok' };
}

# Vue code

<template>
  <div class="demo">
    <div>
      Todo: <input v-model.trim="todo" type="text" maxlength="30" size="30" />
      <button @click="add">Add</button>
    </div>

    <table>
      <tr><th>ID</th><th>Todo</th><th>Status</th><th>Delete</th></tr>
      <tr v-for="item in todos">
        <td>{{item.id}}</td>
        <td>{{item.todo}}</td>
        <td>{{item.done ? 'Completed' : 'Pending'}}</td>
        <td><button @click="del(item.id)">Delete</button></td>
      </tr>
    </table>
    <div class="tips">Hit F12 to access Developer Tools and view the console logs.</div>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      todo: '',
      todos: []
    }
  },
  mounted() {
    this.getList();
  },
  methods: {
    getList() {
      axios.get('https://some.api.com/todo').then(res => (this.todos = res.data));
    },

    async add() {
      if (!this.todo) {
        return alert('please input a todo item.');
      }

      const api = 'https://some.api.com/todo?action=add&todo='+this.todo;

      await axios.get(api).then(res => alert('Result:' + res.data.msg));
      this.todo = '';
      this.getList();
    },

    async del(id) {
      const sure = window.confirm('Are you sure?');
      if (!sure) return;

      const api = 'https://some.api.com/todo?action=del&id='+id;

      await axios.get(api).then(res => alert('Result:' + res.data.msg));
      this.getList();
    }
  }
}
</script>
<style scoped>

</style>
Last update: July 13, 2023 22:53