server.ts 2.38 KB
import { createServer, Model } from "miragejs";
import { ModelDefinition } from "miragejs/-types";

interface Item {
  id: string;
  is_folder: boolean;
  name: string;
  mime_type: string | null;
  path: string | null;
  parent: string | null;
  user_id: string;
  size: number;
  is_deleted: boolean;
  created_timestamp: string;
  updated_timestamp: string;
  status: boolean;
}

interface SharedItem {
  id: string;
  file_id: string;
  until: string;
  password: string;
}

interface User {
  id: string;
  user_id: string;
  name: string;
  password: string;
  total_size: number;
  current_size: number;
}

const ItemModel: ModelDefinition<Item> = Model;
const SharedItemModel: ModelDefinition<SharedItem> = Model;
const UserModel: ModelDefinition<User> = Model;

createServer({
  models: {
    item: ItemModel,
    shared_item: SharedItemModel,
    user: UserModel,
  },

  factories: {},

  routes() {
    this.namespace = "api";

    this.get("/items/:item_id/children", (schema, request) => {
      const directory = schema.find("item", request.params.item_id);
      if (!directory || !directory.is_folder) {
        return {
          status: 404,
          message: "Not Found",
        };
      }

      const list = schema.where("item", { parent: directory.id }).models;
      return {
        status: 200,
        data: {
          ...directory.attrs,
          count: list.length,
          list,
        },
      };
    });
  },

  seeds(server) {
    const user = server.create("user", {
      id: "1",
      user_id: "test",
      name: "테스트",
      password: "password",
      total_size: 1024 * 1024 * 1024 * 5, // 5GB
      current_size: 1024 * 1024 * 1024 * 1, // 1GB
    });

    const rootDir = server.create("item", {
      id: "1",
      is_folder: true,
      name: "root",
      mime_type: null,
      path: null,
      parent: null,
      user_id: user.id,
      size: 0,
      is_deleted: false,
      created_timestamp: "2020-05-14T06:20:44Z",
      updated_timestamp: "2020-05-14T06:20:44Z",
      status: true,
    });

    server.create("item", {
      id: "2",
      is_folder: false,
      name: "image.jpg",
      mime_type: "image/jpeg",
      path: "",
      parent: rootDir.id,
      user_id: user.id,
      size: 1024 * 1024 * 5,
      is_deleted: false,
      created_timestamp: "2020-05-14T06:20:44Z",
      updated_timestamp: "2020-05-14T06:20:44Z",
      status: true,
    });
  },
});