Как сгенерировать JSDoc для функции `pipe`d ES6 - PullRequest
10 голосов
/ 12 октября 2019

У меня есть функция в стиле ES6, которая определяется с помощью композиции функций с asyncPipe.

import { getItemAsync } from 'expo-secure-store';

const asyncPipe = (...fns) => x => fns.reduce(async (y, f) => f(await y), x);

const getToken = () => getItemAsync('token');

const liftedGetToken = async ({ ...rest }) => ({
  token: await getToken(),
  ...rest,
});

const liftedFetch = ({ body, route, token, method = 'GET' } = {}) =>
  fetch(route, {
    ...(body && { body: JSON.stringify(body) }),
    headers: {
      'Content-Type': 'application/json',
      ...(token && { Authorization: `Bearer ${token}` }),
    },
    method,
  });

const json = res => res.json();

/**
 * @method
 * @param {Object} fetchSettings the settings for the fetch request
 * @param {Object} fetchSettings.body the body of the request
 * @param {string} fetchSettings.route the URL of the request
 * @param {string} fetchSettings.method the method of the request
 * @param {string} fetchSettings.token should only be used for testing and unauthenticated requests
 */
const request = asyncPipe(liftedGetToken, liftedFetch, json);

Как вы можете видеть, я пытался добавить описание JSDoc к нему. Но когда я использую его где-либо, мой редактор, VSCode, не предлагает его параметры. Как вы объявляете такие функции с помощью JSDoc? И как мне получить параметры для этой функции для работы с Intellisense?

Ответы [ 2 ]

6 голосов
/ 20 октября 2019

VSCode попытается отобразить комментарий анонимной функции внутри asyncPipe. Если вы добавите комментарий JSDoc внутрь него, вы увидите поведение:

const asyncPipe = (...fns) =>
  /**
   * My asyncPipe description
   * @param {Object} x Any object
   */
  x => fns.reduce(async (y, f) => f(await y), x);

const request = asyncPipe(liftedGetToken, liftedFetch, json);

example

К сожалению, в JSDoc нет способа переопределить документациюанонимная функция, которую вы пытались сделать. Однако вы можете заставить свои намерения использовать VSCode следующим образом, обратите внимание, что это приводит к дополнительному вызову функции:

const doRequest = asyncPipe(liftedGetToken, liftedFetch, json);

/**
 * @method
 * @param {Object} fetchSettings the settings for the fetch request
 * @param {Object} fetchSettings.body the body of the request
 * @param {string} fetchSettings.route the URL of the request
 * @param {string} fetchSettings.method the method of the request
 * @param {string} fetchSettings.token should only be used for testing and unauthenticated requests
 */
const request = fetchSettings => doRequest(fetchSettings);

solution example

1 голос
/ 26 октября 2019

VSCode использует движок TypeScript под капотом, который не очень хорош для вывода типов из композиций функций, и, как вы видели, не распознает бессмысленную композицию как объявление функции.

Есливам нужны подсказки типа, вы можете указать аргументы для составной функции, обернув заостренную функцию вокруг нее.

Я бы написал это примерно так - примечание: значения по умолчанию делают JSDoc ненужным для подсказок типа, нов любом случае вы можете сохранить JSDoc для описания. Также убедитесь, что сбои, вызванные откатами значений по умолчанию, приводят к адекватному обмену сообщениями об ошибках.

/**
  * http request with JSON parsing and token management.
  * @param {Object} fetchSettings the settings for the fetch request
  * @param {Object} fetchSettings.body the body of the request
  * @param {string} fetchSettings.route the URL of the request
  * @param {string} fetchSettings.method the method of the request
  * @param {string} fetchSettings.token should only be used for testing and unauthenticated requests
  */
const request = ({
  body = {},
  route = '',
  method = 'GET',
  token = ''
}) => asyncPipe(liftedGetToken, liftedFetch, json)({
  body, route, method, token
});
...