Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

use-upbit-api

Package Overview
Dependencies
Maintainers
1
Versions
25
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

use-upbit-api - npm Package Compare versions

Comparing version 2.0.0 to 2.0.1

lib/src/functions/isArrayOfImarketCodes.d.ts

7

lib/src/hooks/useWsOrderbook.d.ts

@@ -1,2 +0,2 @@

import { IOrderbook, ImarketCodes } from '../interfaces';
import { IOrderbook, ImarketCodes, OBOptionsInterface } from '../interfaces';
/**

@@ -10,6 +10,3 @@ * useWsOrderbook is a custom hook that connects to a WebSocket API

*/
declare function useWsOrderbook(targetMarketCodes: ImarketCodes[], options?: {
throttle_time: number;
debug: boolean;
}): {
declare function useWsOrderbook(targetMarketCodes: ImarketCodes, onError?: (error: Error) => void, options?: OBOptionsInterface): {
socket: WebSocket | null;

@@ -16,0 +13,0 @@ isConnected: boolean;

@@ -10,2 +10,4 @@ "use strict";

const socketDataEncoder_1 = __importDefault(require("../functions/socketDataEncoder"));
const isImarketCodes_1 = __importDefault(require("../functions/isImarketCodes"));
// extend extend OptionsInterface
/**

@@ -19,5 +21,5 @@ * useWsOrderbook is a custom hook that connects to a WebSocket API

*/
function useWsOrderbook(targetMarketCodes, options = { throttle_time: 400, debug: false }) {
function useWsOrderbook(targetMarketCodes, onError, options = {}) {
const { throttle_time = 400, debug = false } = options;
const SOCKET_URL = 'wss://api.upbit.com/websocket/v1';
const { throttle_time } = options;
const socket = (0, react_1.useRef)(null);

@@ -29,3 +31,3 @@ const buffer = (0, react_1.useRef)([]);

try {
const lastBuffers = (0, getLastBuffers_1.default)(buffer.current, targetMarketCodes.length);
const lastBuffers = (0, getLastBuffers_1.default)(buffer.current, [targetMarketCodes].length);
lastBuffers && setSocketData(lastBuffers[0]);

@@ -35,3 +37,3 @@ buffer.current = [];

catch (error) {
throw new Error();
console.error(error);
}

@@ -42,6 +44,6 @@ }, throttle_time), [targetMarketCodes]);

try {
if (targetMarketCodes.length > 1) {
throw new Error("[Error] | 'Length' of Target Market Codes should be only 'one' in 'orderbook' and 'trade'. you can request only 1 marketcode's data, when you want to get 'orderbook' or 'trade' data.");
if (!(0, isImarketCodes_1.default)(targetMarketCodes)) {
throw new Error('targetMarketCodes does not have the correct interface');
}
if (targetMarketCodes.length > 0 && !socket.current) {
if ([targetMarketCodes].length > 0 && !socket.current) {
socket.current = new WebSocket(SOCKET_URL);

@@ -52,3 +54,3 @@ socket.current.binaryType = 'arraybuffer';

setIsConnected(true);
if (options.debug)
if (debug)
console.log('[completed connect] | socket Open Type: ', 'orderbook');

@@ -60,7 +62,7 @@ if (((_a = socket.current) === null || _a === void 0 ? void 0 : _a.readyState) == 1) {

type: 'orderbook',
codes: targetMarketCodes.map(code => code.market),
codes: [targetMarketCodes.market],
},
];
socket.current.send(JSON.stringify(sendContent));
if (options.debug)
if (debug)
console.log('message sending done');

@@ -73,3 +75,3 @@ }

buffer.current = [];
if (options.debug)
if (debug)
console.log('connection closed');

@@ -79,3 +81,3 @@ };

const error = event.error;
if (options.debug)
if (debug)
console.error('[Error]', error);

@@ -103,3 +105,11 @@ };

catch (error) {
throw new Error();
if (error instanceof Error) {
if (onError) {
onError(error);
}
else {
console.error(error);
throw error;
}
}
}

@@ -106,0 +116,0 @@ }, [targetMarketCodes]);

@@ -1,2 +0,2 @@

import { ITicker, ImarketCodes } from '../interfaces';
import { ITicker, ImarketCodes, TKOptionsInterface } from '../interfaces';
/**

@@ -10,6 +10,3 @@ * useWsTicker is a custom hook that connects to a WebSocket API

*/
declare function useWsTicker(targetMarketCodes: ImarketCodes[], options?: {
throttle_time: number;
debug: boolean;
}): {
declare function useWsTicker(targetMarketCodes: ImarketCodes[], onError?: (error: Error) => void, options?: TKOptionsInterface): {
socket: WebSocket | null;

@@ -16,0 +13,0 @@ isConnected: boolean;

@@ -12,2 +12,3 @@ "use strict";

const updateSocketData_1 = __importDefault(require("../functions/updateSocketData"));
const isArrayOfImarketCodes_1 = __importDefault(require("../functions/isArrayOfImarketCodes"));
/**

@@ -21,5 +22,5 @@ * useWsTicker is a custom hook that connects to a WebSocket API

*/
function useWsTicker(targetMarketCodes, options = { throttle_time: 400, debug: false }) {
function useWsTicker(targetMarketCodes, onError, options = {}) {
const { throttle_time = 400, debug = false } = options;
const SOCKET_URL = 'wss://api.upbit.com/websocket/v1';
const { throttle_time } = options;
const socket = (0, react_1.useRef)(null);

@@ -45,2 +46,5 @@ const buffer = (0, react_1.useRef)([]);

try {
if (!(0, isArrayOfImarketCodes_1.default)(targetMarketCodes)) {
throw new Error('targetMarketCodes does not have the correct interface');
}
if (targetMarketCodes.length > 0 && !socket.current) {

@@ -52,3 +56,3 @@ socket.current = new WebSocket(SOCKET_URL);

setIsConnected(true);
if (options.debug)
if (debug)
console.log('[completed connect] | socket Open Type: ', 'ticker');

@@ -64,3 +68,3 @@ if (((_a = socket.current) === null || _a === void 0 ? void 0 : _a.readyState) == 1) {

socket.current.send(JSON.stringify(sendContent));
if (options.debug)
if (debug)
console.log('message sending done');

@@ -74,3 +78,3 @@ }

buffer.current = [];
if (options.debug)
if (debug)
console.log('connection closed');

@@ -104,3 +108,11 @@ };

catch (error) {
throw new Error();
if (error instanceof Error) {
if (onError) {
onError(error);
}
else {
console.error(error);
throw error;
}
}
}

@@ -123,3 +135,3 @@ }, [targetMarketCodes]);

catch (error) {
console.log(error);
console.error(error);
}

@@ -126,0 +138,0 @@ }, [loadingBuffer]);

@@ -1,2 +0,2 @@

import { ITrade, ImarketCodes } from '../interfaces';
import { ITrade, ImarketCodes, TROptionsInterface } from '../interfaces';
/**

@@ -11,7 +11,3 @@ * useWsTrade is a custom hook that connects to a WebSocket API

*/
declare function useWsTrade(targetMarketCodes: ImarketCodes[], options?: {
throttle_time: number;
max_length_queue: number;
debug: boolean;
}): {
declare function useWsTrade(targetMarketCodes: ImarketCodes, onError?: (error: Error) => void, options?: TROptionsInterface): {
socket: WebSocket | null;

@@ -18,0 +14,0 @@ isConnected: boolean;

@@ -10,2 +10,3 @@ "use strict";

const socketDataEncoder_1 = __importDefault(require("../functions/socketDataEncoder"));
const isImarketCodes_1 = __importDefault(require("../functions/isImarketCodes"));
/**

@@ -20,5 +21,5 @@ * useWsTrade is a custom hook that connects to a WebSocket API

*/
function useWsTrade(targetMarketCodes, options = { throttle_time: 400, max_length_queue: 100, debug: false }) {
function useWsTrade(targetMarketCodes, onError, options = {}) {
const { throttle_time = 400, max_length_queue = 100, debug = false } = options;
const SOCKET_URL = 'wss://api.upbit.com/websocket/v1';
const { throttle_time, max_length_queue } = options;
const socket = (0, react_1.useRef)(null);

@@ -35,3 +36,3 @@ const buffer = (0, react_1.useRef)([]);

catch (error) {
throw new Error();
console.error(error);
}

@@ -42,6 +43,6 @@ }, throttle_time), [targetMarketCodes]);

try {
if (targetMarketCodes.length > 1) {
throw new Error("[Error] | 'Length' of Target Market Codes should be only 'one' in 'orderbook' and 'trade'. you can request only 1 marketcode's data, when you want to get 'orderbook' or 'trade' data.");
if (!(0, isImarketCodes_1.default)(targetMarketCodes)) {
throw new Error('targetMarketCodes does not have the correct interface');
}
if (targetMarketCodes.length > 0 && !socket.current) {
if ([targetMarketCodes].length > 0 && !socket.current) {
socket.current = new WebSocket(SOCKET_URL);

@@ -52,3 +53,3 @@ socket.current.binaryType = 'arraybuffer';

setIsConnected(true);
if (options.debug)
if (debug)
console.log('[completed connect] | socket Open Type: ', 'trade');

@@ -60,7 +61,7 @@ if (((_a = socket.current) === null || _a === void 0 ? void 0 : _a.readyState) == 1) {

type: 'trade',
codes: targetMarketCodes.map(code => code.market),
codes: [targetMarketCodes.market],
},
];
socket.current.send(JSON.stringify(sendContent));
if (options.debug)
if (debug)
console.log('message sending done');

@@ -73,3 +74,3 @@ }

buffer.current = [];
if (options.debug)
if (debug)
console.log('connection closed');

@@ -101,3 +102,11 @@ };

catch (error) {
throw new Error();
if (error instanceof Error) {
if (onError) {
onError(error);
}
else {
console.error(error);
throw error;
}
}
}

@@ -104,0 +113,0 @@ }, [targetMarketCodes]);

@@ -93,1 +93,14 @@ export interface ImarketCodes {

}
export interface OptionsInterface {
debug?: boolean;
}
export interface OBOptionsInterface extends OptionsInterface {
throttle_time?: number;
}
export interface TKOptionsInterface extends OptionsInterface {
throttle_time?: number;
}
export interface TROptionsInterface extends OptionsInterface {
throttle_time?: number;
max_length_queue?: number;
}

@@ -42,4 +42,5 @@ "use strict";

require("@testing-library/jest-dom/extend-expect");
const debugTest = false;
const TestFetchMarketCodeComponent = () => {
const { isLoading, marketCodes } = (0, useFetchMarketCode_1.default)({ debug: true });
const { isLoading, marketCodes } = (0, useFetchMarketCode_1.default)({ debug: debugTest });
return (React.createElement("div", null, isLoading ? (React.createElement("p", null, "Loading...")) : (marketCodes.length > 0 && (React.createElement("ul", { "data-testid": "market-codes" }, marketCodes.map((code, index) => (React.createElement("li", { key: index },

@@ -46,0 +47,0 @@ code.market,

@@ -44,11 +44,18 @@ "use strict";

require("@testing-library/jest-dom/extend-expect");
const TestOrderbookComponent = () => {
const [marketCode, _] = (0, react_1.useState)([
{
market: 'KRW-BTC',
korean_name: '비트코인',
english_name: 'Bitcoin',
},
]);
const { isConnected, socketData } = (0, useWsOrderbook_1.default)(marketCode);
const ErrorBoundary_1 = __importDefault(require("./ErrorBoundary"));
const debugTest = false;
const TestOrderbookComponent = ({ customMarketCode, onError, }) => {
const [marketCode, setMarketCode] = (0, react_1.useState)({
market: 'KRW-BTC',
korean_name: '비트코인',
english_name: 'Bitcoin',
});
(0, react_1.useEffect)(() => {
if (customMarketCode) {
setMarketCode(() => customMarketCode);
}
}, [customMarketCode]);
const { isConnected, socketData } = (0, useWsOrderbook_1.default)(marketCode, onError, {
debug: debugTest,
});
return (React.createElement("div", null,

@@ -63,14 +70,15 @@ isConnected ? React.createElement("p", null, "Connected") : React.createElement("p", null, "Not Connected"),

describe('useWsOrderbook hook', () => {
it('renders connection status and received socket data', () => __awaiter(void 0, void 0, void 0, function* () {
// Test invalid targetMarketCodes
it('useWsOrderbook should throw error with invalid targetMarketCodes', () => {
const onError = jest.fn();
const invalidTargetMarketCodes = {
market: 'test_market',
korean_name: 'test_korean',
};
// Render the TestOrderbookComponent
(0, react_2.render)(React.createElement(TestOrderbookComponent, null));
// Check if the connection status is displayed
const connectionStatus = react_2.screen.getByText(/Connected|Not Connected/i);
expect(connectionStatus).toBeInTheDocument();
// Wait for the socket data to be displayed
const socketDataList = yield react_2.screen.findByTestId('socket-data', {}, { timeout: 5000 });
// Check if the socket data is displayed
expect(socketDataList).toBeInTheDocument();
expect(socketDataList.children.length).toBeGreaterThan(0);
}));
(0, react_2.render)(React.createElement(ErrorBoundary_1.default, { onError: onError },
React.createElement(TestOrderbookComponent, { customMarketCode: invalidTargetMarketCodes, onError: onError })));
expect(onError).toHaveBeenCalled();
expect(onError.mock.calls[0][0].message).toBe('targetMarketCodes does not have the correct interface');
});
it('received socket data correctly', () => __awaiter(void 0, void 0, void 0, function* () {

@@ -77,0 +85,0 @@ // Render the TestOrderbookComponent

@@ -43,4 +43,6 @@ "use strict";

require("@testing-library/jest-dom/extend-expect");
const TestTickerComponentConnection = () => {
const [marketCode, _] = (0, react_1.useState)([
const ErrorBoundary_1 = __importDefault(require("./ErrorBoundary"));
const debugTest = false;
const TestTickerComponent = ({ customMarketCode, onError, }) => {
const [marketCode, setMarketCode] = (0, react_1.useState)([
{

@@ -52,3 +54,11 @@ market: 'KRW-BTC',

]);
const { isConnected, socketData } = (0, useWsTicker_1.default)(marketCode);
(0, react_1.useEffect)(() => {
if (customMarketCode) {
console.log('here', customMarketCode);
setMarketCode(() => customMarketCode);
}
}, [customMarketCode]);
const { isConnected, socketData } = (0, useWsTicker_1.default)(marketCode, onError, {
debug: debugTest,
});
return (React.createElement("div", null,

@@ -62,5 +72,25 @@ isConnected ? React.createElement("p", null, "Connected") : React.createElement("p", null, "Not Connected"),

describe('useWsTicker hook', () => {
// Test invalid targetMarketCodes
it('useWsTicker should throw error with invalid targetMarketCodes', () => {
const onError = jest.fn();
const invalidTargetMarketCodes = [
{
market: 'KRW-BTC',
korean_name: '비트코인',
english_name: 'Bitcoin',
},
{
market: 'KRW-ETH',
korean_name: '이더리움',
},
];
// Render the TestOrderbookComponent
(0, react_2.render)(React.createElement(ErrorBoundary_1.default, { onError: onError },
React.createElement(TestTickerComponent, { customMarketCode: invalidTargetMarketCodes, onError: onError })));
expect(onError).toHaveBeenCalled();
expect(onError.mock.calls[0][0].message).toBe('targetMarketCodes does not have the correct interface');
});
it('renders connection status and received socket data', () => __awaiter(void 0, void 0, void 0, function* () {
// Render the TestTickerComponentConnection
(0, react_2.render)(React.createElement(TestTickerComponentConnection, null));
// Render the TestTickerComponent
(0, react_2.render)(React.createElement(TestTickerComponent, null));
// Check if the connection status is displayed

@@ -67,0 +97,0 @@ const connectionStatus = react_2.screen.getByText(/Connected|Not Connected/i);

@@ -44,11 +44,19 @@ "use strict";

require("@testing-library/jest-dom/extend-expect");
const TestTradeComponent = () => {
const [marketCode, _] = (0, react_1.useState)([
{
market: 'KRW-BTC',
korean_name: '비트코인',
english_name: 'Bitcoin',
},
]);
const { isConnected, socketData } = (0, useWsTrade_1.default)(marketCode);
const react_3 = require("react");
const ErrorBoundary_1 = __importDefault(require("./ErrorBoundary"));
const debugTest = false;
const TestTradeComponent = ({ customMarketCode, onError, }) => {
const [marketCode, setMarketCode] = (0, react_1.useState)({
market: 'KRW-BTC',
korean_name: '비트코인',
english_name: 'Bitcoin',
});
(0, react_3.useEffect)(() => {
if (customMarketCode) {
setMarketCode(() => customMarketCode);
}
}, [customMarketCode]);
const { isConnected, socketData } = (0, useWsTrade_1.default)(marketCode, onError, {
debug: debugTest,
});
return (React.createElement("div", null,

@@ -63,2 +71,15 @@ isConnected ? React.createElement("p", null, "Connected") : React.createElement("p", null, "Not Connected"),

describe('useWsTrade hook', () => {
// Test invalid targetMarketCodes
it('useWsTrade should throw error with invalid targetMarketCodes', () => {
const onError = jest.fn();
const invalidTargetMarketCodes = {
market: 'test_market',
korean_name: 'test_korean',
};
// Render the TestTradeComponent
(0, react_2.render)(React.createElement(ErrorBoundary_1.default, { onError: onError },
React.createElement(TestTradeComponent, { customMarketCode: invalidTargetMarketCodes, onError: onError })));
expect(onError).toHaveBeenCalled();
expect(onError.mock.calls[0][0].message).toBe('targetMarketCodes does not have the correct interface');
});
it('renders connection status and received socket data', () => __awaiter(void 0, void 0, void 0, function* () {

@@ -65,0 +86,0 @@ // Render the TestTradeComponent

{
"name": "use-upbit-api",
"version": "2.0.0",
"version": "2.0.1",
"description": "This is React Custom Hook for upbit api",

@@ -5,0 +5,0 @@ "main": "lib/index.js",

@@ -14,2 +14,4 @@ # use-upbit-api

[_Coverage Status_ →](https://devkangminhyeok.github.io/use-upbit-api/)
[_View Demo_ →](https://devkangminhyeok.github.io/React-Upbit-API-Example/total-example)

@@ -19,4 +21,2 @@

---
## Install

@@ -26,4 +26,2 @@

---
## Hooks

@@ -43,4 +41,2 @@

---
## useFetchMarketCode

@@ -56,2 +52,8 @@

## ⚠️ CAUTIONs IN WEBSOCKET API
targetMarketCode should be state in react (useState, ...), if not, unexpectable error can occur.
Do not use just constant or variable.
## useWsTicker

@@ -62,4 +64,14 @@

```tsx
const [targetMarketCode, _] = useState([
{
market: 'KRW-BTC',
korean_name: '비트코인',
english_name: 'Bitcoin',
},
...
]);
const {socket, isConnected, socketData} = useWsTicker(
targetMarketCode,
targetMarketCode, // should be array
onError, // onError?: (error: Error) => void // optional, user for using ErrorBoundary
(options = {throttle_time: 400, debug: false}), // default option, can be modified.

@@ -74,4 +86,11 @@ );

```tsx
const [targetMarketCode, _] = useState({
market: 'KRW-BTC',
korean_name: '비트코인',
english_name: 'Bitcoin',
});
const {socket, isConnected, socketData} = useWsOrderbook(
targetMarketCode,
targetMarketCode, // should be above form object
onError, // onError?: (error: Error) => void // optional, user for using ErrorBoundary
(options = {throttle_time: 400, debug: false}), // default option, can be modified.

@@ -87,4 +106,11 @@ );

```tsx
const [targetMarketCode, _] = useState({
market: 'KRW-BTC',
korean_name: '비트코인',
english_name: 'Bitcoin',
});
const {socket, isConnected, socketData} = useWsTrade(
targetMarketCode,
targetMarketCode, // should be above form object
onError, // onError?: (error: Error) => void // optional, user for using ErrorBoundary
(options = {throttle_time: 400, max_length_queue: 100, debug: false}), // default option, can be modified.

@@ -96,6 +122,23 @@ );

If you want to contribute to `use-upbit-api`, please contact me <rkdalsgur032@unist.ac.kr>
Thank you for your interest in contributing to use-upbit-api. Before you begin writing code, it is important that you share your intention to contribute with the team, based on the type of contribution
1. You want to **propose a new feature** and implement it.
- Post about your intended feature in an [issue](https://github.com/devKangMinHyeok/use-upbit-api/issues), then implement it.
- We suggest that the branch name that you implement is better to be {type}/{issue number}/{issue name}. ex) feature/118/githubAction, bugfix/120/typo
2. You want to **implement a feature or bug-fix** for an outstanding issue.
- Search for your issue in the [Mips-simulator-js issue list](https://github.com/devKangMinHyeok/use-upbit-api/issues).
- Pick an issue and comment that you'd like to work on the feature or bug-fix.
- If you need more context on a particular issue, please ask and we shall provide.
3. **Open pull request**
- You implement and test your feature or bug-fix, please submit a Pull Request to [https://github.com/mipsSimulatorUNIST/simulator/pulls](https://github.com/devKangMinHyeok/use-upbit-api/pulls) with some test case.
- Once a pull request is accepted and CI is passing, there is nothing else you need to do. we will check and merge the PR for you.
**_Always opening_** to join this project for developing this library.
❗️[_ISSUE_ &rarr;](https://github.com/devKangMinHyeok/use-upbit-api/issues)
✅ [_Pull Request_ &rarr;](https://github.com/devKangMinHyeok/use-upbit-api/pulls)
## License
Licensed under the MIT License, Copyright © 2022-present MinHyeok Kang.
SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc