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

컨텍스트 객체 레퍼런스

원문 보기 위키 갱신

컨텍스트 객체 레퍼런스 (Context object reference)

이 문서는 Insomnia 플러그인이 Insomnia와 소통하고 상호작용할 수 있게 도와주는 컨텍스트 객체의 메서드를 정리한 레퍼런스예요. 컨텍스트 객체를 쓰면 요청 헤더를 바꾸거나 알림을 띄우는 같은 작업을 할 수 있어요. 요청과 응답을 다루는 context.request와 context.response부터 데이터를 저장하는 context.store, 앱 정보를 담은 context.app, 환경 데이터인 context.data, 네트워크 관련 context.network까지 섹션별 인터페이스 정의와 예제 코드를 확인할 수 있어요

출처: 문서

본문

context.request

요청 컨텍스트에는 Insomnia 요청과 상호작용하기 위한 헬퍼가 들어 있어요.

interface RequestContext {
    getId(): string;
    getName(): string;
    getUrl(): string;
    setUrl(url: string): void;
    getMethod(): string;
    setMethod(method: string): void;
    getHeaders(): Array<{ name: string, value: string }>;
    getHeader(name: string): string | null;
    hasHeader(name: string): boolean;
    removeHeader(name: string): void;
    setHeader(name: string, value: string): void;
    addHeader(name: string, value: string): void;
    getParameter(name: string): string | null;
    getParameters(): Array<{name: string, value: string}>;
    setParameter(name: string, value: string): void;
    hasParameter(name: string): boolean;
    addParameter(name: string, value: string): void;
    removeParameter(name: string): void;
    getBody(): RequestBody;
    setBody(body: RequestBody): void;
    getEnvironmentVariable(name: string): any;
    getEnvironment(): Object;
    setAuthenticationParameter(name: string, value: string): void;
    getAuthentication(): Object;
    setCookie(name: string, value: string): void;
    settingSendCookies(enabled: boolean): void;
    settingStoreCookies(enabled: boolean): void;
    settingEncodeUrl(enabled: boolean): void;
    settingDisableRenderRequestBody(enabled: boolean): void;
    settingFollowRedirects(enabled: boolean): void;
};

interface RequestBody {
  mimeType?: string;
  text?: string;
  fileName?: string;
  params?: RequestBodyParameter[];
}

interface RequestBodyParameter {
  name: string;
  value: string;
  description?: string;
  disabled?: boolean;
  multiline?: string;
  id?: string;
  fileName?: string;
  type?: string;
}

context.request 예제

모든 POST 요청에 Content-Type 헤더를 설정해 보세요:

// Request hook to set header on every request
module.exports.requestHooks = [
  context => {
    if (context.request.getMethod().toUpperCase() === 'POST') {
      context.request.setHeader('Content-Type', 'application/json');
    }
  }
];

요청 본문을 수정해 보세요:

// Replace "FOO" with "BAR" within a request body before sending
const regexp = new RegExp(/FOO/, 'g');

module.exports.requestHooks = [
  context => {
    const body = context.request.getBody();
    context.request.setBody({
      ...body,
      text: body.text.replace(regexp, 'BAR'),
    });
  }
];

요청 본문을 덮어써 보세요:

module.exports.requestHooks = [
  context => {
    context.request.setBody({
      mimeType: 'application/json',
      text: JSON.stringify({ foo: 'bar' }),
    });
  }
];

context.response

응답 컨텍스트에는 Insomnia 응답과 상호작용하기 위한 헬퍼가 들어 있어요.

interface ResponseContext {
    getRequestId(): string;
    getStatusCode(): number;
    getStatusMessage(): string;
    getBytesRead(): number;
    getTime(): number;
    getBody(): Buffer | null;
    getBodyStream(): Readable;
    setBody(body: Buffer);
    getHeader(name: string): string | Array<string> | null;
    getHeaders(): Array<{ name: string, value: string }> | undefined;
    hasHeader(name: string): boolean,
}

응답 본문은 NodeJS Buffers와 함께 동작해요. 플러그인을 통해 응답 본문을 변경하려면 Buffer로 변환했다가 다시 되돌리는 과정이 필요해요.

context.response 예제

응답을 파일에 기록해 보세요:

const fs = require('fs');

// Response hook to save response to file
module.exports.responseHooks = [
  context => {
   context.response.getBodyStream().pipe(
      fs.createWriteStream('./response-body.txt')
    );
  }
];

다음 예제는 responseHooks를 사용하며, NodeJS Buffers를 활용해 다음 작업을 수행하는 방법을 보여줘요:

  • Buffer를 문자열로 변환해요
  • 문자열을 JS 객체로 파싱해요
  • 다음과 같은 방법으로 응답을 수정해요:
    • 난수를 생성해요
    • 모달을 통해 사용자에게 정보를 입력받아요
  • JS 객체를 문자열로 변환한 뒤 Buffer로 변환해요
const bufferToJsonObj = buf => JSON.parse(buf.toString('utf-8'));
const jsonObjToBuffer = obj => Buffer.from(JSON.stringify(obj), 'utf-8');

module.exports.responseHooks = [
  async ctx => {
    try{
      const resp = bufferToJsonObj(ctx.response.getBody());
      
      // Modify
      resp.__randomNumber = Math.random();

      // If you want something from a user, use a prompt:
      const promptResult = await ctx.app.prompt('Type something', { defaultValue: 'abcd' });
      resp.__customValue = promptResult;

      ctx.response.setBody(jsonObjToBuffer(resp));
    } catch {
      // no-op
    }
  }
]

context.store

플러그인은 스토리지 컨텍스트를 통해 영속 데이터를 저장할 수 있어요. 저장된 데이터는 그것을 저장한 플러그인만 접근할 수 있어요.

interface StoreContext {
    hasItem(key: string): Promise<boolean>;
    setItem(key: string, value: string): Promise<void>;
    getItem(key: string): Promise<string | null>;
    removeItem(key: string): Promise<void>;
    clear(): Promise<void>;
    all(): Promise<Array<{ key: string, value: string }>>;
}

context.app

앱 컨텍스트에는 애플리케이션 전역에서 사용할 수 있는 일반적인 헬퍼 모음이 들어 있어요.

interface AppContext {
    getInfo(): { version: string, platform: string };
    alert(title: string, message?: string): Promise<void>;

    dialog(title: string, body: HTMLElement, options?: {
        onHide?:() => void;
        tall?: boolean;
        skinny?: boolean;
        wide?: boolean;
    }): void;

    prompt(title: string, options?: {
        label?: string;
        defaultValue?: string;
        submitName?: string;
        cancelable?: boolean;
    }): Promise<string>;

    getPath(name: string): string;
    
    showSaveDialog(options?: {
        defaultPath?: string;
    }): Promise<string | null>;

    clipboard: {
      readText(): string;
      writeText(text: string): void;
      clear(): void;
    };
}

context.data

데이터 컨텍스트에는 Insomnia 워크스페이스 가져오기 및 내보내기와 관련된 헬퍼가 들어 있어요.

interface ImportOptions {
    workspaceId?: string;
    workspaceScope?: 'design' | 'collection';
}

interface DataContext {
    import: {
        uri(uri: string, options?: ImportOptions): Promise<void>;
        raw(text: string, options?: ImportOptions): Promise<void>;
    },
    export: {
        insomnia(options?: { 
            includePrivate?: boolean,
            format?: 'json' | 'yaml',
        }): Promise<string>;
        har(options?: { includePrivate?: boolean }): Promise<string>;
    }
}

context.network

네트워크 컨텍스트에는 네트워크 요청 전송과 관련된 헬퍼가 들어 있어요.

interface NetworkContext {
    sendRequest(request: Request): Promise<Response>;
}

관련 리소스

더 알아보기 (Learn more)

  • 플러그인의 기본 개념부터 만드는 방법을 먼저 훑어보고 싶을 때 참고하기 좋아요 — Plugins
  • 컨텍스트 객체를 훅과 액션에서 실제로 어떻게 활용하는지 보여주는 문서예요 — Hooks and actions
  • 컨텍스트 외에 플러그인에서 쓸 수 있는 API 전반을 정리한 레퍼런스예요 — Plugin reference