New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

rest-api-kit

Package Overview
Dependencies
Maintainers
1
Versions
52
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

rest-api-kit - npm Package Compare versions

Comparing version 0.0.18 to 0.0.19

10

dist/index.d.ts

@@ -16,4 +16,6 @@ type MethodType = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";

data: unknown;
response: unknown;
error: unknown;
isSuccess: boolean;
extra: unknown;
};

@@ -55,2 +57,10 @@ type QueryHookReturnType = [(body?: Record<string, string>) => void, state: RequestStateType];

/**
* @name useRest
* @description A hook that takes charge of making requests, saving the state where necessary.
* and showing errors accordingly.
* @returns An array containing a trigger functions which takes an argument of an object which serves as a body to the api request and a state object.
* @returns { trigger }: A function that saves data to the store. Takes two parameters: id (string) and data (unknown). Returns void.
* @returns { state }: An object that includes the state of the api request.
*/
declare function useRest(url: string, paramsFromBase?: Partial<IOptions>, options?: Partial<RestOptionsType>): QueryHookReturnType;

@@ -57,0 +67,0 @@

112

dist/index.js

@@ -115,9 +115,31 @@ "use strict";

};
var applyChecks = (params, response) => {
if (!params.successCondition(response)) {
return { type: "error", response };
}
return {
type: "success",
response: params.transformResponse(response)
};
};
var load = (dispatch, url, params, body) => {
const paramForHere = { ...params };
delete paramForHere.successCondition;
delete paramForHere.transformResponse;
dispatch({
type: "extra/save",
payload: {
url,
body,
isFired: true,
...params
}
});
};
// src/hooks/useStore.ts
var import_react = require("react");
var initState = {
store: {}
};
function reducer(state, { type, payload }) {
// src/lib/reducers/store.ts
function storeReducer(state, { type, payload }) {
switch (type) {

@@ -133,4 +155,13 @@ case "store/save":

}
var store_default = storeReducer;
// src/lib/states/store.ts
var initStoreState = {
store: {}
};
var store_default2 = initStoreState;
// src/hooks/useStore.ts
function useStore() {
const [state, dispatch] = (0, import_react.useReducer)(reducer, initState);
const [state, dispatch] = (0, import_react.useReducer)(store_default, store_default2);
console.log("store state => ", state);

@@ -152,10 +183,4 @@ return {

// src/hooks/useRest.ts
var initState2 = {
isLoading: false,
data: void 0,
error: void 0,
isSuccess: false
};
function reducer2(state, { type, payload }) {
// src/lib/reducers/rest.ts
function restReducer(state, { type, payload }) {
switch (type) {

@@ -174,2 +199,4 @@ case "loading/start":

return { ...state, error: void 0 };
case "extra/save":
return { ...state, extra: void 0 };
default:

@@ -179,2 +206,25 @@ return "Unrecognized command";

}
var rest_default = restReducer;
// src/lib/states/rest.ts
var initRestState = {
isLoading: false,
data: void 0,
response: void 0,
error: void 0,
isSuccess: false,
extra: {
body: {},
isFired: false,
url: "",
preferCachevalue: false,
updates: [],
method: "GET",
saveToCache: false,
endpointName: ""
}
};
var rest_default2 = initRestState;
// src/hooks/useRest.ts
var defaultOptions = {

@@ -189,10 +239,4 @@ preferCachevalue: false,

};
var applyChecks = (params, dispatch, response) => {
if (params.successCondition(response)) {
dispatch({ type: "data/error", payload: response });
}
return params.transformResponse(response);
};
function useRest(url, paramsFromBase = {}, options = {}) {
const [state, dispatch] = (0, import_react2.useReducer)(reducer2, initState2);
const [state, dispatch] = (0, import_react2.useReducer)(rest_default, rest_default2);
const { save: saveToStore, get: getFromStore, clear: clearFromStore } = useStore();

@@ -203,2 +247,3 @@ const trigger = async (body = {}) => {

url = getBaseUrl(url, options?.baseUrl);
load(dispatch, url, params, body);
let storeIdentifier = `${options.baseUrl || ""}&${params.endpointName}`;

@@ -208,4 +253,14 @@ if (params.preferCachevalue) {

if (cachedResult) {
applyChecks(params, dispatch, cachedResult);
return;
const { type: checkType2, response: payload2 } = applyChecks(params, cachedResult);
if (checkType2 === "error") {
dispatch({
type: "data/error",
payload: payload2
});
return;
}
dispatch({
type: "data/success",
payload: payload2
});
}

@@ -217,6 +272,17 @@ }

const response = await makeRequest(concatenateParamsWithUrl(url, body));
dispatch({ type: "data/success", payload: applyChecks(params, dispatch, response) });
if (params?.saveToCache) {
saveToStore(storeIdentifier, response, { ...defaultOptions, ...params });
}
const { type: checkType, response: payload } = applyChecks(params, response);
if (checkType === "error") {
dispatch({
type: "data/error",
payload
});
return;
}
dispatch({
type: "data/success",
payload
});
if (params.updates.length > 0) {

@@ -223,0 +289,0 @@ clearMultipleIds(params.updates, options.baseUrl || "", (id) => clearFromStore(id));

{
"name": "rest-api-kit",
"version": "0.0.18",
"version": "0.0.19",
"main": "dist/index.js",

@@ -5,0 +5,0 @@ "module": "dist/index.mjs",

@@ -6,14 +6,68 @@ # Rest Api Kit

rest-api-kit is available for use as a package on npm:
```npm i rest-api-kit```
```sh
npm i rest-api-kit
```
or yarn:
```yarn add rest-api-kit```
```sh
yarn add rest-api-kit
```
## What's in it?
Rest API kit comes with the following hooks:
`"useRest"`: creates a base for apis. This hook returns a trigger function and a state object. Each works as follows:
Rest API kit comes with a base and hooks. The hooks are created from endpoint objects that are injected with the createEndpoints method as you'll see in the usage section of this documentation.
## Usage
### Import createRestBase
Import the `createRestBase` from `rest-api-kit` like so:
```ts
import { createRestBase } from "rest-api-kit";
```
If you use the `saveToCache` option when using a trigger function, then we create a cache entry based entirely on the url passed in from the same trigger. Whether that cache entry is new is dependent on:
1. If there is a cache with the same url as its key already, we then check if the `preferCacheValue` is set to `true`. If it is, we supply you the value in the cache and not createa new entry
2. If there is no cache with the same url as its key already, we make the request and create a new cache entry with the url. At this point even if `preferCacheValue` is set to true, it doesn't matter because we are only just creating the cache entry.
### Assign it
assign it to a variable like so:
```ts
const api = createRestBase({ baseUrl: "https://jsonplaceholder.typicode.com" });
```
### Inject the endpoints
Create the endpoints at the base of your file so it gets loaded in soon as the app launches.
```ts
const injector = api.createEndpoints((builder) => ({
getATodo: builder({
url: "/todos/1",
params: {
preferCachevalue: false,
saveToCache: true,
successCondition: (data) => {
if (data.completed) {
return true;
}
return false;
},
transformResponse: (data) => {
// always return data;
return data;
}
}
}),
createTodo: builder({
url: "/post",
params: {
method: 'POST',
updates: ['getATodo'],
}
})
}));
```
### Use it.
In the components that you need it in, you can use it like so:
```ts
const [getATodo, state] = useGetATodo();
const { data } = state;
console.log(state, "<= state");
useEffect(() => {
getATodo();
}, [])
```

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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