Socket
Socket
Sign inDemoInstall

@lskjs/apiquery

Package Overview
Dependencies
39
Maintainers
11
Versions
104
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @lskjs/apiquery

http/s + websockets api client for Web, Node.js and React Native throw fetch or axios


Version published
Maintainers
11
Install size
2.80 MB
Created

Readme

Source

LSK.js – apiquery

@lskjs/apiquery – http/s + websockets api client for Web, Node.js and React Native throw fetch or axios

LSK logo NPM version NPM downloads NPM Dependency count Have TypeScript types Have tree shaking NPM Package size Package size Ask us in Telegram


Table of contents

⌨️ Install

# yarn
yarn i @lskjs/apiquery axios lodash

# npm
npm i @lskjs/apiquery axios lodash

Apiquery

http + websockets api client for Web, Node.js and React Native

const api = new ApiClient({
  url: 'http://localhost:8080',
  base: '/api/v1',
  authToken: '#1234567890',
});
const api = new ApiClient({
  base: '/api/v1',
});

api.fetch('messages')   // GET /api/v1/messages
api.fetch('/messages')  // GET /messages
api.fetch('messages', {
  base: '/api/v2'
})  // GET /api/v2/messages

api.fetch('isuvorov.ru')  // GET /api/v1/isuvorov.ru
api.fetch('//isuvorov.ru/api/v1')  // GET //isuvorov.ru/api/v1
const api = new ApiClient({
  url: 'http://localhost:8080',
  base: '/api/v1',
});

api.fetch('messages')   // GET http://localhost:8080/api/v1/messages
api.fetch('/messages')  // GET http://localhost:8080/messages
api.fetch('messages', {
  base: '/api/v2'
})  // GET http://localhost:8080/api/v2/messages

api.fetch('isuvorov.ru')  // GET http://localhost:8080/api/v1/isuvorov.ru
api.fetch('//isuvorov.ru/api/v1')  // GET http://isuvorov.ru/api/v1


const api2 = new ApiClient({
  url: 'https://localhost:8080',
  base: '/api/v1',
});
api2.fetch('//isuvorov.ru/api/v1')  // GET https://isuvorov.ru/api/v1

Headers

По стандарту отправляются хедеры, которые маркируют пакет как JSON. Если вам нгеобходимо отправить пакет, без Content-Type: application/json; charset=utf-8, необходимо воспользоваться следующим способом.

Это может быть полезно например для загрузки изображения методом POST multipart/form-data


const api = new ApiClient({
  base: '/api/v1',
});

await api.fetch('/upload', {
  method: 'POST',
  headers: {
    'Content-Type': '!',
  },
  body,
});

afterFetch

Функция обрабатывает данные которые приходят в fetch. Возвращает или payload результата (JSON объект) или генерирует ошибку.

Стандартное поведение - генерировать ошибку при статусе пакета >= 400, или при наличии объекта err в JSON ответе.

Для того чтобы изменить поведение обработки ошибок на определенных старницах, можно передать функцию (function) которая особым образом обрабатывает ошибки.

Предположим что, для страницы /api/v1/users, в случае отсутсвия пользователей нам возвращяется ошибка Error 404, вместо [] и нам нужно проигнорировать стандартное поведение в этом случае. При этом, чтобы при других видах ошибок - поведение оставалось прежним.


const api = new ApiClient({
  base: '/api/v1',
});

api.fetch('users', {
  afterFetch: function (data) {
    const { res } = data;
    if (res.status === 404) {
      return []
    }
    return this.afterFetch(data)
  }
})



throwError


const api = new ApiClient({
  base: '/api/v1',
});

api.fetch('users', {
  afterFetch: function (data) {
    const { res } = data;
    if (res.status === 404) {
      return []
    }
    return this.afterFetch(data)
  }
})

ws

Работа с сокетами: socket.io

const api = new ApiClient({
  base: '/api/v1',
});

const s1 = api.ws('messages') // WS /api/v1/messages
s1.on('message', (data) => {
  console.log(data);
})
const s2 = api.ws('messages', options) // look options here: https://socket.io/docs/client-api/#manager


📖 License

This project is licensed under the MIT License - see the LICENSE file for details

👥 Contributors


Igor Suvorov

💻 🎨 🤔

👏 Contributing

  1. Fork it (https://github.com/yourname/yourproject/fork)
  2. Create your feature branch (git checkout -b features/fooBar)
  3. Commit your changes (git commit -am 'feat(image): Add some fooBar')
  4. Push to the branch (git push origin feature/fooBar)
  5. Create a new Pull Request

📮 Any questions? Always welcome :)

FAQs

Last updated on 08 Oct 2021

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc