npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ilb/node_rest

v2.0.2

Published

Node REST utils

Downloads

85

Readme

Асинхронное выполнение кода

Установка

$ npm install --save @bb/node-async

Оглавление

  1. run
  2. checkResult
  3. clearResult

Роутинг

Использование

Для одиночного роута

export default router(createScope).post(CreateOffer).put(EditOffer).build();

Для группы роутов:

export default (() =>
  router(createScope).setPrefix('/api/offers/:uuid/')
    .post('', CreateOffer)
    .put('monitor', MonitorOffer)
    .get('templates/:code', DownloadTemplates)
    .build()
)();
  • createScope - замыкание, которое выполняется перед запуском usecase
  • CreateOffer, MonitorOffer, DownloadTemplates - классы usecase

Юзкейсы

Должны наследоваться от ApiUsecase, AccessorUsecase или FileUsecase

export default class EditOffer extends ApiUsecase {

  constructor({ ...scope }) {
    super(scope);
    this.permission = 'update_offers';
  }

  async initialize({ uuid }) {
    // constructor
  }
  
  async process() {
    // do something
  }

  async schema() {
    // ajv schema for validation
  }
}
export default class MonitorOffer extends AccessorUsecase {
  constructor({ ...scope }) {
    super(scope);
  }

  async process() {
    // ...
    if (condition) {
      return { /* ... */ }; // завершение работы accessor
    }

    return null; // продолжение работы accessor
  }
}
export default class DownloadTemplates extends FileUsecase {
  constructor({ ...scope }) {
    super(scope);
  }

  async process({ uuid }) {
    // ...
    return { file, contentType, filename };
  }
}

run

Функция запускает выполнение переданной функции или промиса и возвращает UUID операции.

run(fn, needClear = true)

Аргументы:

  • fn: (Function | Promise) - обычная функция или асинхронная функция (async fn() ...) или промис.
  • needClear: (boolean) = true - флаг определяет требуется ли удалять файлы с результатами операции после того как checkResult вернул результат вызывающей стороне (по умолчанию true - т.е. удаляются). Срабатывает после возвращения результатов даже если функция завершилась с ошибкой (произошло исключение throw new Error) или успешном выполнении функции.

Ответ:

UUID операции.

Исключения (throw new Error):

Ошибки связанные с созданием файла во временной директории ОС с PID-ом процесса.

checkResult

Функция проверки результата выполнения операции.

checkResult(uuid)

Аргументы:

uuid: string - UUID операции из функции run.

Ответ:

  • Если сервис отработал без ошибок:

    {
      status: string,
      data: string
    }

    , где status = complete, data - результат операции.

  • Если ошибки в процессе выполнения:

    {
      status: string,
      message: string
    }

    , где status = error, message - текст сообщения об ошибке.

  • Если запущенная операция всё ещё выполняется:

    {
      status: string
    }

    , где status = launched.

Исключения (throw new Error):

Ошибки чтения файла результата, файла ошибок, файла c PID процесса или ошибки при выполнении проверки наличия процесса по PID-у.

clearResult

Удаляет файлы результатов операции.

clearResult(): void

Аргументы:

Отсутствуют.

Ответ:

Отсутствует.

Исключения (throw new Error):

Отсутствуют (любые ошибки связанные с удалением файлов не возвращаются).