Преглед на файлове

添加mock service worker,axios,search service

Kevin Jiang преди 3 години
родител
ревизия
e8918bd01b

Файловите разлики са ограничени, защото са твърде много
+ 1598 - 30
package-lock.json


+ 6 - 1
package.json

@@ -15,6 +15,7 @@
   "dependencies": {
     "@types/lodash": "^4.14.188",
     "ant-design-vue": "^3.2.13",
+    "axios": "^1.1.3",
     "pinia": "^2.0.21",
     "vue": "^3.2.38",
     "vue-router": "^4.1.5"
@@ -34,6 +35,7 @@
     "eslint-plugin-vue": "^9.3.0",
     "jsdom": "^20.0.0",
     "less": "^4.1.3",
+    "msw": "^0.48.1",
     "npm-run-all": "^4.1.5",
     "sass": "^1.56.0",
     "start-server-and-test": "^1.14.0",
@@ -41,5 +43,8 @@
     "vite": "^3.0.9",
     "vitest": "^0.23.0",
     "vue-tsc": "^0.40.7"
+  },
+  "msw": {
+    "workerDirectory": "public"
   }
-}
+}

+ 303 - 0
public/mockServiceWorker.js

@@ -0,0 +1,303 @@
+/* eslint-disable */
+/* tslint:disable */
+
+/**
+ * Mock Service Worker (0.48.1).
+ * @see https://github.com/mswjs/msw
+ * - Please do NOT modify this file.
+ * - Please do NOT serve this file on production.
+ */
+
+const INTEGRITY_CHECKSUM = '3d6b9f06410d179a7f7404d4bf4c3c70'
+const activeClientIds = new Set()
+
+self.addEventListener('install', function () {
+  self.skipWaiting()
+})
+
+self.addEventListener('activate', function (event) {
+  event.waitUntil(self.clients.claim())
+})
+
+self.addEventListener('message', async function (event) {
+  const clientId = event.source.id
+
+  if (!clientId || !self.clients) {
+    return
+  }
+
+  const client = await self.clients.get(clientId)
+
+  if (!client) {
+    return
+  }
+
+  const allClients = await self.clients.matchAll({
+    type: 'window',
+  })
+
+  switch (event.data) {
+    case 'KEEPALIVE_REQUEST': {
+      sendToClient(client, {
+        type: 'KEEPALIVE_RESPONSE',
+      })
+      break
+    }
+
+    case 'INTEGRITY_CHECK_REQUEST': {
+      sendToClient(client, {
+        type: 'INTEGRITY_CHECK_RESPONSE',
+        payload: INTEGRITY_CHECKSUM,
+      })
+      break
+    }
+
+    case 'MOCK_ACTIVATE': {
+      activeClientIds.add(clientId)
+
+      sendToClient(client, {
+        type: 'MOCKING_ENABLED',
+        payload: true,
+      })
+      break
+    }
+
+    case 'MOCK_DEACTIVATE': {
+      activeClientIds.delete(clientId)
+      break
+    }
+
+    case 'CLIENT_CLOSED': {
+      activeClientIds.delete(clientId)
+
+      const remainingClients = allClients.filter((client) => {
+        return client.id !== clientId
+      })
+
+      // Unregister itself when there are no more clients
+      if (remainingClients.length === 0) {
+        self.registration.unregister()
+      }
+
+      break
+    }
+  }
+})
+
+self.addEventListener('fetch', function (event) {
+  const { request } = event
+  const accept = request.headers.get('accept') || ''
+
+  // Bypass server-sent events.
+  if (accept.includes('text/event-stream')) {
+    return
+  }
+
+  // Bypass navigation requests.
+  if (request.mode === 'navigate') {
+    return
+  }
+
+  // Opening the DevTools triggers the "only-if-cached" request
+  // that cannot be handled by the worker. Bypass such requests.
+  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
+    return
+  }
+
+  // Bypass all requests when there are no active clients.
+  // Prevents the self-unregistered worked from handling requests
+  // after it's been deleted (still remains active until the next reload).
+  if (activeClientIds.size === 0) {
+    return
+  }
+
+  // Generate unique request ID.
+  const requestId = Math.random().toString(16).slice(2)
+
+  event.respondWith(
+    handleRequest(event, requestId).catch((error) => {
+      if (error.name === 'NetworkError') {
+        console.warn(
+          '[MSW] Successfully emulated a network error for the "%s %s" request.',
+          request.method,
+          request.url,
+        )
+        return
+      }
+
+      // At this point, any exception indicates an issue with the original request/response.
+      console.error(
+        `\
+[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
+        request.method,
+        request.url,
+        `${error.name}: ${error.message}`,
+      )
+    }),
+  )
+})
+
+async function handleRequest(event, requestId) {
+  const client = await resolveMainClient(event)
+  const response = await getResponse(event, client, requestId)
+
+  // Send back the response clone for the "response:*" life-cycle events.
+  // Ensure MSW is active and ready to handle the message, otherwise
+  // this message will pend indefinitely.
+  if (client && activeClientIds.has(client.id)) {
+    ;(async function () {
+      const clonedResponse = response.clone()
+      sendToClient(client, {
+        type: 'RESPONSE',
+        payload: {
+          requestId,
+          type: clonedResponse.type,
+          ok: clonedResponse.ok,
+          status: clonedResponse.status,
+          statusText: clonedResponse.statusText,
+          body:
+            clonedResponse.body === null ? null : await clonedResponse.text(),
+          headers: Object.fromEntries(clonedResponse.headers.entries()),
+          redirected: clonedResponse.redirected,
+        },
+      })
+    })()
+  }
+
+  return response
+}
+
+// Resolve the main client for the given event.
+// Client that issues a request doesn't necessarily equal the client
+// that registered the worker. It's with the latter the worker should
+// communicate with during the response resolving phase.
+async function resolveMainClient(event) {
+  const client = await self.clients.get(event.clientId)
+
+  if (client?.frameType === 'top-level') {
+    return client
+  }
+
+  const allClients = await self.clients.matchAll({
+    type: 'window',
+  })
+
+  return allClients
+    .filter((client) => {
+      // Get only those clients that are currently visible.
+      return client.visibilityState === 'visible'
+    })
+    .find((client) => {
+      // Find the client ID that's recorded in the
+      // set of clients that have registered the worker.
+      return activeClientIds.has(client.id)
+    })
+}
+
+async function getResponse(event, client, requestId) {
+  const { request } = event
+  const clonedRequest = request.clone()
+
+  function passthrough() {
+    // Clone the request because it might've been already used
+    // (i.e. its body has been read and sent to the client).
+    const headers = Object.fromEntries(clonedRequest.headers.entries())
+
+    // Remove MSW-specific request headers so the bypassed requests
+    // comply with the server's CORS preflight check.
+    // Operate with the headers as an object because request "Headers"
+    // are immutable.
+    delete headers['x-msw-bypass']
+
+    return fetch(clonedRequest, { headers })
+  }
+
+  // Bypass mocking when the client is not active.
+  if (!client) {
+    return passthrough()
+  }
+
+  // Bypass initial page load requests (i.e. static assets).
+  // The absence of the immediate/parent client in the map of the active clients
+  // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
+  // and is not ready to handle requests.
+  if (!activeClientIds.has(client.id)) {
+    return passthrough()
+  }
+
+  // Bypass requests with the explicit bypass header.
+  // Such requests can be issued by "ctx.fetch()".
+  if (request.headers.get('x-msw-bypass') === 'true') {
+    return passthrough()
+  }
+
+  // Notify the client that a request has been intercepted.
+  const clientMessage = await sendToClient(client, {
+    type: 'REQUEST',
+    payload: {
+      id: requestId,
+      url: request.url,
+      method: request.method,
+      headers: Object.fromEntries(request.headers.entries()),
+      cache: request.cache,
+      mode: request.mode,
+      credentials: request.credentials,
+      destination: request.destination,
+      integrity: request.integrity,
+      redirect: request.redirect,
+      referrer: request.referrer,
+      referrerPolicy: request.referrerPolicy,
+      body: await request.text(),
+      bodyUsed: request.bodyUsed,
+      keepalive: request.keepalive,
+    },
+  })
+
+  switch (clientMessage.type) {
+    case 'MOCK_RESPONSE': {
+      return respondWithMock(clientMessage.data)
+    }
+
+    case 'MOCK_NOT_FOUND': {
+      return passthrough()
+    }
+
+    case 'NETWORK_ERROR': {
+      const { name, message } = clientMessage.data
+      const networkError = new Error(message)
+      networkError.name = name
+
+      // Rejecting a "respondWith" promise emulates a network error.
+      throw networkError
+    }
+  }
+
+  return passthrough()
+}
+
+function sendToClient(client, message) {
+  return new Promise((resolve, reject) => {
+    const channel = new MessageChannel()
+
+    channel.port1.onmessage = (event) => {
+      if (event.data && event.data.error) {
+        return reject(event.data.error)
+      }
+
+      resolve(event.data)
+    }
+
+    client.postMessage(message, [channel.port2])
+  })
+}
+
+function sleep(timeMs) {
+  return new Promise((resolve) => {
+    setTimeout(resolve, timeMs)
+  })
+}
+
+async function respondWithMock(response) {
+  await sleep(response.delay)
+  return new Response(response.body, response)
+}

+ 5 - 0
src/main.ts

@@ -9,6 +9,11 @@ import "ant-design-vue/dist/antd.less";
 
 import "./assets/main.css";
 
+import { worker } from './mocks/browser';
+if (process.env.NODE_ENV === 'development') {
+  worker.start({onUnhandledRequest: 'bypass'})
+}
+
 const app = createApp(App);
 
 app.use(Antd);

+ 5 - 0
src/mocks/browser.ts

@@ -0,0 +1,5 @@
+import { setupWorker } from "msw";
+import { handlers } from "./handlers";
+
+// This configures a Service Worker with the given request handlers.
+export const worker = setupWorker(...handlers);

+ 16 - 0
src/mocks/handlers.ts

@@ -0,0 +1,16 @@
+import { rest } from 'msw';
+
+const urlPrefix = "/api";
+
+export const handlers = [
+  rest.post(`${urlPrefix}/search`, (req, res, ctx) => {
+    return res(
+      ctx.status(200),
+      ctx.json({
+        status: 200,
+        msg: '',
+        data: [1, 2, 3]
+      })
+    );
+  }),
+];

+ 1 - 1
src/router/index.ts

@@ -33,7 +33,7 @@ const router = createRouter({
       children: [
         {
           path: "index",
-          name: "Search",
+          name: "SearchIndex",
           component: () => import("../views/search/SearchView.vue")
         },
         {

+ 37 - 0
src/services/httpClient.ts

@@ -0,0 +1,37 @@
+import { message } from "ant-design-vue";
+import axios, { AxiosError, type AxiosRequestConfig } from "axios";
+import _ from "lodash";
+
+const urlPrefix = "/api";
+
+const httpClient = axios.create({
+  baseURL: urlPrefix,
+  timeout: 60000,
+});
+
+// 添加请求拦截器
+httpClient.interceptors.request.use(function (config: AxiosRequestConfig) {
+  // 在发送请求之前做些什么
+  // const token = localStorage.getItem('token');
+  // config.headers.Authorization = token;
+  // config.url = urlPrefix + "/" + _.trimStart(config.url, '/');
+  return config;
+}, function (error) {
+  // 对请求错误做些什么
+  return Promise.reject(error);
+});
+
+// 添加响应拦截器
+httpClient.interceptors.response.use(function (response) {
+  // 对响应数据做点什么
+  return response;
+}, function (error: AxiosError) {
+  // 对响应错误做点什么
+  if (error.response?.status == 404) {
+    message.error("请求参数错误!");
+  }
+
+  return Promise.reject(error);
+});
+
+export default httpClient;

+ 12 - 0
src/services/search.service.ts

@@ -0,0 +1,12 @@
+import type { SearchResult } from "@/types/search.types";
+import type { AxiosResponse } from "axios";
+import httpClient from "./httpClient";
+
+function search(query: string): Promise<AxiosResponse<SearchResult>> {
+  const params = { query };
+  return httpClient.post("/search", params);
+}
+
+export default {
+  search,
+}

+ 3 - 0
src/types/search.types.ts

@@ -0,0 +1,3 @@
+export interface SearchResult {
+  total: number,
+}

+ 35 - 11
src/views/search/SearchResultView.vue

@@ -1,20 +1,14 @@
 <script setup lang="ts">
-import { onMounted, onUnmounted, ref } from "vue";
-import { useRouter } from "vue-router";
-import type { SelectProps } from "ant-design-vue";
+import { onMounted, onUnmounted, ref, watch } from "vue";
+import { useRoute, useRouter } from "vue-router";
+import { message, type SelectProps } from "ant-design-vue";
 import { useSideBarStore } from "@/stores/side-bar";
 import SearchResultItem from "./components/SearchResultItem.vue";
+import searchService from "@/services/search.service";
 
 const sideBarStore = useSideBarStore();
 
-onMounted(() => {
-  // 收起左侧边栏
-  sideBarStore.setCollapse(true);
-});
-
-onUnmounted(() => {
-  sideBarStore.setCollapse(false);
-});
+const route = useRoute();
 
 // 关键词
 const keyword = ref("");
@@ -22,9 +16,27 @@ const keyword = ref("");
 const field = ref("TP");
 // 路由
 const router = useRouter();
+
+function doSearch() {
+  if (keyword.value.length == 0) {
+    keyword.value = (route.query.kw as string) || "";
+    if (keyword.value.length == 0) {
+      router.push({name: "SearchIndex"});
+      return;
+    }
+  }
+  searchService.search("query").then((resp) => {
+    console.log(resp.data);
+  }).catch((err) => {
+    console.log(err);
+  })
+}
+
 // 搜索事件监听
 const onSearch = () => {
   router.push({name: 'SearchResult', query: { kw: keyword.value }});
+
+  doSearch();
 }
 // 搜索框字段选择项列表
 const fieldOptions = ref<SelectProps['options']>([
@@ -52,6 +64,18 @@ function handleSortChange(event: any) {
 }
 
 const currentPage = ref(1);
+
+onMounted(() => {
+  // 收起左侧边栏
+  sideBarStore.setCollapse(true);
+
+  doSearch();
+});
+
+onUnmounted(() => {
+  sideBarStore.setCollapse(false);
+});
+
 </script>
 
 <template>

+ 7 - 2
src/views/search/SearchView.vue

@@ -1,5 +1,5 @@
 <script setup lang="ts">
-import type { SelectProps } from "ant-design-vue";
+import { message, type SelectProps } from "ant-design-vue";
 import { ref } from "vue";
 import { useRouter } from "vue-router";
 
@@ -10,7 +10,12 @@ const field = ref("TP");
 const router = useRouter();
 
 const onSearch = () => {
-  router.push({name: 'SearchResult', query: { kw: keyword.value }});
+  const kwd = keyword.value.trim();
+  if (kwd.length == 0) {
+    message.warning("请输入查询关键词");
+    return;
+  }
+  router.push({name: 'SearchResult', query: { kw: kwd }});
 }
 
 const fieldOptions = ref<SelectProps['options']>([