본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

훅과 액션

원문 보기 위키 갱신

훅과 액션 (Hooks and actions)

커스텀 플러그인에 추가 기능을 얹을 수 있게 해주는 훅과 액션을 다루는 문서예요. 훅은 요청이나 응답 시점에 호출되는 함수이고, 액션은 사이드바의 요청이나 폴더 메뉴에 사용자 지정 동작을 추가하는 기능이에요. RequestHook과 ResponseHook 구현 방법부터 요청, 폴더, 워크스페이스, 문서 액션 예제까지 코드와 함께 차근차근 살펴봐요

출처: 문서

본문

요청 및 응답 훅

플러그인은 특정 이벤트가 발생했을 때 호출되는 훅 함수를 구현할 수 있어요. 현재 플러그인은 RequestHook과 ResponseHook이라는 두 가지 유형의 훅을 내보낼 수 있어요.

interface RequestHook {
    app: AppContext;
    request: Request;
};

interface ResponseHook {
    app: AppContext;
    response: Response;
}

// Hooks are exported as an array of hook functions that get 
// called with the appropriate plugin API context.
module.exports.requestHooks = Array<(context: RequestHook) => void>;
module.exports.responseHooks = Array<(context: ResponseHook) => void>;

요청 액션

요청 액션 플러그인을 정의하면 요청 드롭다운 컨텍스트 메뉴(사이드바에서 요청을 마우스 오른쪽 버튼으로 클릭) 하단에 액션을 추가할 수 있어요.

interface RequestAction {
    label: string;
    action: (context: Context, models: { 
        requestGroup: RequestGroup;
        request: Request;
    }): void | Promise<void>;
    icon?: string;
};

// Request actions are exported as an array of objects
module.exports.requestActions = Array<RequestAction>

요청 액션 예시

사이드바에서 요청을 마우스 오른쪽 버튼으로 클릭했을 때 나타나는 드롭다운 메뉴에 요청 데이터 보기 옵션을 추가해요:

module.exports.requestActions = [
  {
    label: 'See request data',
    action: async (context, data) => {
      const { request } = data;
      const html = `<code>${JSON.stringify(request)}</code>`;
      context.app.showGenericModalDialog('Results', { html });
    },
  },
];

사이드바에서 요청을 마우스 오른쪽 버튼으로 클릭했을 때 나타나는 드롭다운 메뉴에 요청 보내기 옵션을 추가해요:

module.exports.requestActions = [
  {
    label: "Send request",
    action: async (context, data) => {
      const { request } = data;
      const response = await context.network.sendRequest(request);
      const html = `<code>${request.name}: ${response.statusCode}</code>`;
      context.app.showGenericModalDialog("Results", { html });
    },
  },
];

폴더 액션

폴더(요청 그룹) 액션 플러그인을 정의하면 폴더 드롭다운 메뉴 하단에 액션을 추가할 수 있어요.

interface RequestGroupAction {
    label: string;
    action: (context: Context, models: { 
        requestGroup: RequestGroup; 
        requests: Array<Request>;
    }): Promise<void>;
};

// Folder actions are exported as an array of objects
module.exports.requestGroupActions = Array<RequestGroupAction>

폴더 액션 예시

요청 폴더를 클릭했을 때 나타나는 드롭다운 메뉴에 요청 보내기 옵션을 추가해요. 요청 보내기는 해당 폴더의 모든 요청을 한 번에 보내요:

module.exports.requestGroupActions = [
  {
    label: 'Send Requests',
    action: async (context, data) => {
      const { requests } = data;

      let results = [];
      for (const request of requests) {
        const response = await context.network.sendRequest(request);
        results.push(`<li>${request.name}: ${response.statusCode}</li>`);
      }

      const html = `<ul>${results.join('\n')}</ul>`;

      context.app.showGenericModalDialog('Results', { html });
    },
  },
];

워크스페이스 액션

워크스페이스 액션 플러그인을 정의하면 API Collection 설정 드롭다운에 액션을 추가할 수 있어요. 이 액션은 스펙 포함 여부와 상관없이 모든 API Collection에 적용돼요.

참고: "Workspace"는 코드베이스에서 API Collection을 가리킬 때 사용하는 이름이에요. Insomnia 13.2 및 이전 버전에서는 문서와 컬렉션을 모두 가리켰는데, 이 둘은 이제 API Collection으로 통합됐어요.

interface WorkspaceAction {
    label: string;
    action: (context: Context, models: { 
        workspace: Workspace;
        requestGroup: Array<RequestGroup>,;
        requests: Array<Request>;
    }): Promise<void>;
};

// Workspace actions are exported as an array of objects
module.exports.workspaceActions = Array<WorkspaceAction>;

워크스페이스 액션 예시

현재 API Collection을 내보내는 사용자 지정 옵션을 API Collection 드롭다운 메뉴에 추가해요:

const fs = require('fs');

module.exports.workspaceActions = [{
  label: 'My Plugin Action',
  icon: 'fa-star',
  action: async (context, models) => {
    const ex = await context.data.export.insomnia({
      includePrivate: false,
      format: 'json',
      workspace: models.workspace,
    });

    fs.writeFileSync('./export.json', ex);
  },
}];

문서 액션

스펙이 포함된 API Collection의 대시보드 카드 컨텍스트 메뉴에 액션을 추가할 수 있어요. 이 액션은 해당 스펙을 전달받기 때문에, 스펙이 없는 API Collection에서는 사용할 수 없어요.

interface DocumentAction {
    label: string,
    action: (
      context: Context,
      spec: {
        contents: Record<string, any>;
        rawContents: string;
        format: string;
        formatVersion: string;
      }
    ): void | Promise<void>;
    hideAfterClick?: boolean;
};

// Document actions are exported as an array of objects
module.exports.documentActions = Array<DocumentAction>;

관련 리소스

더 알아보기 (Learn more)

  • 플러그인 개발의 전체적인 구조와 시작 방법을 먼저 훑어보고 싶을 때 좋아요 — Plugins
  • 훅과 액션에서 사용하는 API를 코드 레벨에서 자세히 확인할 수 있어요 — Plugin reference
  • 액션 함수에 전달되는 context 객체의 속성과 사용법을 정리해놨어요 — Context object reference
  • 문서 액션이 지금은 API 컬렉션으로 통합된 배경을 이해하는 데 도움이 돼요 — merged into API Collections