
Product
Introducing Repository Access Permissions and Custom Roles
Socket now supports Custom Roles and Repository Access Permissions so organizations can control who can access specific repositories and actions.
if-service
Advanced tools
Affected versions:
if-service 是一个基于 axios 的轻量 API 服务注册库,适合把接口定义按模块统一管理,并补上网关切换、请求取消、结果缓存、状态监听等能力。
user.login()、order.list() 这种调用方式npm i if-service
如果你要使用 useApi() / usePager(),项目中还需要安装并提供 vue。
import IfService from "if-service";
app.use(IfService, {
env: "local",
gateway: {
default: {
local: "http://localhost:3000",
production: "https://api.example.com",
},
admin: {
local: "http://localhost:3100",
production: "https://admin-api.example.com",
},
},
});
app.use() 本质上会调用内部的 createInstance({ env, gateway }),用于初始化当前运行环境和网关配置。
import { addService } from "if-service";
addService("user", "login", {
url: "/auth/login",
method: "post",
});
addService("user", "profile", {
url: "/user/profile",
method: "get",
});
import { useService } from "if-service";
const $ = useService("user");
const res = await $.login({
username: "demo",
password: "123456",
});
这是这个库最重要的行为约定,建议先看这一节。
response.data,不是完整的 AxiosResponsearraybuffer、blob、stream 时,返回原始 AxiosResponseerr.response,默认不会进入 catchcatchabort() 方法也就是说,同一个接口在不同场景下可能拿到两种形态:
const $ = useService("user");
const res = await $.profile();
// 成功时通常是后端业务对象
// { code, message, data }
// 非 2xx 时通常是 AxiosResponse
// { status, data, headers, config, ... }
如果你要统一判断,推荐优先兼容 status 和 code:
const $ = useService("user");
const result = await $.profile();
const code = result?.status ?? result?.code;
addService(module, apiName, options | url)注册单个接口。
addService("user", "login", {
url: "/auth/login",
method: "post",
});
// 字符串写法等价于只传 url,method 默认 post
addService("user", "logout", "/auth/logout");
options 支持以下字段:
url: 接口地址,支持绝对地址、相对地址、:param 路径参数method: get / post / put / delete / postgetgateway: 网关名称,默认空字符串;最终通过 getGateway() 拼接前缀config: 请求配置对象cache: false | true | string | functionexpired: 缓存秒数,默认 1800cacheMode: LocalStorage / Memory / lscacheAfterRequest: 缓存条件函数,默认 (res) => +res.code === 200useService(module?)读取已注册的服务。
const $ = useService("user");
await $.login({ username: "demo" });
const $$ = useService();
await $$.user.profile();
extendService(module, apis, options)在同一个模块下批量注册接口。
import { extendService } from "if-service";
extendService("user", {
login: "/auth/login@post",
profile: "/user/profile@get",
update: "/user/profile@put",
}, {
gateway: "admin",
});
说明:
apis 的值格式为 url@methodoptions 中除 gateway / authMode 外,其余字段会进入 configregisterService(serviceMap, options)批量注册多个模块,模块名支持带网关后缀。
import { registerService, useService } from "if-service";
registerService({
user: {
login: "/auth/login@post",
profile: "/user/profile@get",
},
report@admin: {
list: "/reports/list@post",
},
});
const $ = useService("user");
const $$ = useService("report");
说明:
module@gateway 时,会自动把该模块挂到对应网关@gateway 时,默认走 defaultAPI(options)直接调用底层请求能力,不经过服务注册。
import { API } from "if-service";
const res = await API({
url: "/health",
method: "get",
gateway: "default",
});
config.headers追加当前请求头:
addService("user", "profile", {
url: "/user/profile",
method: "get",
config: {
headers: {
"x-trace-id": "demo",
},
},
});
config.authMode支持两种模式:
"Bearer": 自动从 document.cookie 中读取 Authorizationfunction: 自定义返回请求头对象addService("user", "profile", {
url: "/user/profile",
method: "get",
config: {
authMode: () => ({
Authorization: "Bearer " + token,
}),
},
});
setGlobalAuthMode(fn)设置全局鉴权头生成函数,所有请求都会合并其返回值。
import { setGlobalAuthMode } from "if-service";
setGlobalAuthMode(() => ({
Authorization: "Bearer " + localStorage.getItem("token"),
}));
setCommonHeader(headers) / getCommonHeader()维护全局公共请求头。
import { setCommonHeader } from "if-service";
setCommonHeader({
"x-app-id": "web-console",
});
config.formData把普通对象转成 FormData 发送:
const $ = useService("user");
$.saveProfile(
{ nickname: "demo", avatar: file },
{ config: { formData: true } }
);
config.file用于文件上传,会强制设置 Content-Type: multipart/form-data,并把参数转为 FormData:
$.upload(
{ file },
{ config: { file: true } }
);
url 支持 :param 占位符,发请求时会从 params 中取值并替换,同时从原对象中移除该字段。
addService("project", "detail", {
url: "/projects/:projectId",
method: "get",
});
const $ = useService("project");
await $.detail({ projectId: 1 });
// 实际请求 /projects/1
createInstance({ env, gateway })手动初始化环境和网关,不依赖 Vue 插件安装:
import { createInstance } from "if-service";
createInstance({
env: "local",
gateway: {
default: {
local: "http://localhost:3000",
production: "https://api.example.com",
},
},
});
缓存发生在 addService() 注册的接口层。
addService("user", "profile", {
url: "/user/profile",
method: "get",
cache: true,
expired: 3600,
cacheMode: "LocalStorage",
});
缓存规则:
cache: true 时,默认 key 为 module.apiNamecache: "custom-key" 时,使用自定义 keycache: (module, apiName, params) => string 时,动态生成 keyPromise.resolve(cachedValue)+res.code === 200 时写入缓存const p = userService.profile();
p.abort();
useCollection()创建一个请求收集器。创建之后发出的请求会被收集,支持统一取消。
import { useCollection } from "if-service";
const collection = useCollection();
userService.profile();
userService.detail({ id: 1 });
collection.abort();
collection.destroy();
说明:
abort(filterFn) 只取消符合条件的请求destroy() 会取消全部请求并销毁当前收集器abortRequests(filterFn?)取消默认全局收集器中的请求:
import { abortRequests } from "if-service";
abortRequests((options) => options.url.includes("/user"));
addWatcher() 用于监听 HTTP 状态码,或后端业务码。
import { addWatcher } from "if-service";
addWatcher(401, (source, response) => {
console.log(source, response);
});
匹配规则:
response.data.coderesponse.statussource.status || source.codeaddWatcher(
(code) => ![200, 401, 500].includes(+code),
(source, response) => {
console.log("unexpected response", source, response);
}
);
说明:
useApi(module, api)返回:
loadererrordataquery(params)import { useApi } from "if-service";
const { loader, error, data, query } = useApi("user", "profile");
query();
usePager(module, api)返回:
loadererrordatapaginationquery(page, initQuery)import { usePager } from "if-service";
const { loader, error, data, pagination, query } = usePager("report", "list");
query(1, { keyword: "demo" });
注意:
vue 的 ref / reactiveuseService()服务调用时可以传第二个参数覆盖注册时配置:
userService.profile(
{},
{
gateway: "admin",
config: {
headers: {
"x-debug": "1",
},
},
}
);
注意:
config,会整体替换注册时的 config运行时代码当前导出如下成员:
IfService Vue 插件对象axiosAPIaddServiceuseServiceuseCollectionextendServicecreateInstancesetGlobalAuthModeregisterServiceaddWatcheruseApiusePagerabortRequestssetCommonHeadergetCommonHeaderregisterService() 或 extendService() 维护接口映射setGlobalAuthMode() 和 setCommonHeader() 注入公共头useCollection() 或 abortRequests() 避免并发脏数据addWatcher()FAQs
全局API服务
The npm package if-service receives a total of 180 weekly downloads. As such, if-service popularity was classified as not popular.
We found that if-service demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Product
Socket now supports Custom Roles and Repository Access Permissions so organizations can control who can access specific repositories and actions.

Product
Socket MCP now lets AI assistants review org alerts, investigate threats using the Socket threat feed, and inspect package files in addition to dependency scoring.

Product
Socket Firewall blocks malicious VS Code and Open VSX extensions before install, protecting developers from compromised editor marketplaces.