@jwork-space/strapi-sdk 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,292 @@
1
+ # @jwork-space/strapi-sdk
2
+
3
+ SDK para Strapi con soporte completo para **TypeScript** y **React Query**.
4
+ Permite realizar operaciones CRUD, manejar paginación, relaciones y personalizar requests fácilmente.
5
+
6
+ ---
7
+
8
+ ## Instalación
9
+
10
+ ```bash
11
+ # Usando pnpm
12
+ pnpm add @jwork-space/strapi-sdk
13
+
14
+ # Usando npm
15
+ npm install @jwork-space/strapi-sdk
16
+ ```
17
+
18
+ ## Importación
19
+
20
+ ```bash
21
+ import {
22
+ StrapiSDK,
23
+ type PaginationResponse,
24
+ type RequestOptions,
25
+ type SerializeOptions,
26
+ type StrapiConfig,
27
+ } from "@jwork-space/strapi-sdk";
28
+
29
+ ```
30
+
31
+ ## Definición de las interfaces
32
+ Para definir las interfaces de tus modelos, puedes usar los autocompletados de TypeScript de los populate y filters:
33
+
34
+ ```bash
35
+ interface Section {
36
+ id: number;
37
+ name: string;
38
+ }
39
+
40
+ interface Category {
41
+ id: number;
42
+ name: string;
43
+ }
44
+
45
+ interface Stock {
46
+ id: number;
47
+ name: string;
48
+ section?: Section | null;
49
+ }
50
+
51
+ interface Product {
52
+ id: number;
53
+ name: string;
54
+ description?: string;
55
+ price: number;
56
+ category?: Category[] | null;
57
+ stocks?: Stock | null;
58
+ }
59
+
60
+ ```
61
+
62
+ ## Configuración básica
63
+
64
+ Antes de usar el SDK, puedes configurar los parámetros de conexión y comportamiento:
65
+ ```bash
66
+ const productStrapiApiConfig: StrapiConfig = {
67
+ /* set only in case of no user proxy */
68
+ baseURL: "http://localhost:1337",
69
+ /* on case use proxy prefix */
70
+ prefix:
71
+ "strapi-api-v2" /* ouput: http://localhost:1337/strapi-api-v2/api/products */,
72
+ /* in case of use uid on create model product */
73
+ onCreate: {
74
+ generateUID: false,
75
+ keyUID: "strapiUID",
76
+ },
77
+ /* default jwr */
78
+ tokenKey: "jwt-strapi",
79
+ /* default on save/update/list-all { body: { data } } */
80
+ wrapBodyInData: false,
81
+ /* remember that is use on response list */
82
+ transformResponse: false,
83
+ /* page size por default when user method listAll, default 15 */
84
+ pageSize: 40,
85
+ defaultQueriesInvalidations: {
86
+ /* default this model (products), buy you can add others: example ['users', 'stocks'] */
87
+ destroy: ["stocks"],
88
+ update: ["stocks"],
89
+ save: ["stocks"],
90
+ },
91
+ };
92
+
93
+ ```
94
+
95
+ ## Ejemplo básico de uso
96
+ ```bash
97
+ export const productAPI = new StrapiSDK<Product>(
98
+ "products",
99
+ productStrapiApiConfig
100
+ );
101
+
102
+ /* example usave method */
103
+
104
+ const requestOptions: RequestOptions<Product> = {
105
+ /* default sort by id:desc */
106
+ sort: "createdAt:desc",
107
+ fields: ["id", "name", "price"],
108
+ populate: {
109
+ category: true,
110
+ stocks: {
111
+ populate: {
112
+ section: true,
113
+ },
114
+ filters: {
115
+ section: {
116
+ id: {
117
+ $eq: 1,
118
+ },
119
+ },
120
+ },
121
+ },
122
+ },
123
+ };
124
+
125
+ export const exampleUsage = async () => {
126
+ const id = 1;
127
+
128
+ /* retornar lista de productos paginados */
129
+ const { data: _data, pagination: _pagination } = await productAPI.listAll(
130
+ requestOptions
131
+ );
132
+
133
+ /* retornar todos de productos de la base de datos y sin paginación */
134
+ const { data: _data, pagination: _pagination } = await productAPI.getAllData(
135
+ requestOptions
136
+ );
137
+
138
+ const requestOptionsOnActions: RequestOptions<Product> = {
139
+ populate: {
140
+ category: true,
141
+ stocks: {
142
+ populate: {
143
+ section: true,
144
+ },
145
+ },
146
+ },
147
+ };
148
+
149
+ const serializeOptionsOnSaveAndUpdate: SerializeOptions = {
150
+ onlyIdForRelations: true,
151
+ preserveRelations: ["stocks"],
152
+ };
153
+
154
+ const _productSaved = await productAPI.save(
155
+ {
156
+ id: 0 /* use cero for create new */,
157
+ name: "product-name",
158
+ description: "product-description",
159
+ price: 100,
160
+ category: [{ id: 1, name: "category-name" }],
161
+ stocks: { id: 1, name: "stock-name" },
162
+ },
163
+ requestOptionsOnActions,
164
+ serializeOptionsOnSaveAndUpdate
165
+ );
166
+
167
+ const _productUpdated = await productAPI.update(
168
+ id,
169
+ {
170
+ id,
171
+ name: "product-name",
172
+ description: "product-description",
173
+ price: 100,
174
+ category: [{ id: 1, name: "category-name" }],
175
+ stocks: { id: 1, name: "stock-name" },
176
+ },
177
+ requestOptionsOnActions,
178
+ serializeOptionsOnSaveAndUpdate
179
+ );
180
+
181
+ /* return boolean */
182
+ const hasDeleted = await productAPI.destroy(id);
183
+ };
184
+
185
+ ```
186
+
187
+ ## Ejemplo extendido: Métodos personalizados
188
+
189
+ Puedes extender el SDK para agregar métodos custom o sobreescribir los existentes:
190
+
191
+ ```bash
192
+ /* example extends SDK Methods */
193
+ class ProductAPI extends StrapiSDK<Product> {
194
+ constructor() {
195
+ super("products", productStrapiApiConfig);
196
+ }
197
+
198
+ /* override default method */
199
+ listAll = async (options?: RequestOptions<Product>) => {
200
+ /* raw response type return:
201
+ data: Product[]
202
+ pagination: {
203
+ page: number
204
+ pageSize: number
205
+ total: number
206
+ totalPages: number
207
+ nextPage: number
208
+ prevPage: number
209
+ }
210
+ */
211
+ return await this.getCall<PaginationResponse<Product>>("products", options);
212
+ };
213
+
214
+ /* exmplay override method save */
215
+ save = async (
216
+ entity: Product,
217
+ requestOptions?: RequestOptions<Product>,
218
+ serializeOptions?: SerializeOptions
219
+ ): Promise<Product> => {
220
+ /* or set your own settings to create */
221
+ if (!entity.id) {
222
+ entity.name = `NEW-${entity.name}`;
223
+ }
224
+ // Llamamos al save original
225
+ return await this.save(entity, requestOptions, serializeOptions);
226
+ };
227
+
228
+ /* exmplay create method save custom */
229
+ saveCustom = async (
230
+ entity: Product,
231
+ requestOptions?: RequestOptions<Product>,
232
+ serializeOptions?: SerializeOptions
233
+ ): Promise<Product> => {
234
+ /* or set your own settings to create */
235
+ if (!entity.id) {
236
+ entity.category = [{ id: 1, name: "category-name" }];
237
+ entity.name = `NEW-${entity.name}`;
238
+ }
239
+ /* you can use methods hhtp */
240
+ /* example */
241
+ return await this.postCall<Product>("products", {
242
+ /* auth default true, (if is false, no send token to backend) */
243
+ auth: false,
244
+ body: entity,
245
+ headers: {
246
+ "Content-Type": "application/json",
247
+ Accept: "application/json",
248
+ /* on case no use default token */
249
+ "Bearer token": "your-token",
250
+ },
251
+ responseType: "json", // default json || 'blob'
252
+ query: {
253
+ extraQuery: {
254
+ "your-query-key": "your-query-value",
255
+ },
256
+ },
257
+ });
258
+ // Llamamos al save original
259
+ return await this.save(entity, requestOptions, serializeOptions);
260
+ };
261
+
262
+ /* new method */
263
+ listAllCustom = async (options?: RequestOptions<Product>) => {
264
+ /* raw response type return:
265
+ data: Product[]
266
+ meta: {
267
+ pagination: {
268
+ page: number
269
+ pageSize: number
270
+ total: number
271
+ totalPages: number
272
+ nextPage: number
273
+ prevPage: number
274
+ }
275
+ }
276
+ */
277
+
278
+ /* the options can be the that */
279
+ return await this.getCall<PaginationResponse<Product>>("products", options);
280
+ };
281
+ }
282
+
283
+ export const productAPIExtended = new ProductAPI();
284
+
285
+ /* example usage methods SDK Methods Custom */
286
+ await productAPIExtended.listAll();
287
+ await productAPIExtended.saveCustom({
288
+ id: 0,
289
+ name: "product-name",
290
+ price: 100,
291
+ });
292
+ ```