@codegenapps/frontend-sdk 1.0.1 → 1.0.3

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 CHANGED
@@ -14,24 +14,24 @@ This SDK is designed to be highly flexible. It dynamically fetches an API specif
14
14
  ## Installation
15
15
 
16
16
  ```bash
17
- npm install frontend-sdk # Replace 'frontend-sdk' with your actual package name on npm
17
+ npm install @codegenapps/frontend-sdk
18
18
  ```
19
19
 
20
20
  ## Quick Start
21
21
 
22
- Here's how to initialize the client and perform a query:
22
+ The following example demonstrates how to initialize the client and perform a query in a standard JavaScript environment.
23
23
 
24
24
  ```javascript
25
- import cga from 'frontend-sdk';
25
+ import cga from '@codegenapps/frontend-sdk';
26
26
 
27
- // 1. Initialize the client
27
+ // 1. Initialize the client (ideally once when your application starts)
28
28
  async function initialize() {
29
29
  await cga.init({
30
30
  // The base URL of your API
31
31
  baseUrl: 'http://localhost:8080/api',
32
32
 
33
33
  // A function that provides your SDK license key
34
- licenseKeyProvider: () => 'YOUR_SDK_LICENSE_KEY',
34
+ licenseKeyProvider: () => 'YOUR_API_KEY',
35
35
 
36
36
  // (Optional) A function that provides the JWT for authenticated requests
37
37
  tokenProvider: () => localStorage.getItem('jwt_token'),
@@ -60,7 +60,133 @@ async function fetchDocuments() {
60
60
  }
61
61
  }
62
62
 
63
- initialize().then(fetchDocuments);
63
+ initialize().then(async () => {
64
+ await fetchDocuments();
65
+ await loginUser(); // 示範登入功能
66
+ });
67
+
68
+ // 3. Perform login
69
+ async function loginUser() {
70
+ const API_KEY = 'YOUR_API_KEY';
71
+ const account = 'test@example.com';
72
+ const password = 'testpassword';
73
+
74
+ try {
75
+ console.log(`嘗試使用帳號: ${account}, API Key: ${API_KEY} 登入...`);
76
+ const { data, error } = await cga.auth.login(account, password, API_KEY);
77
+
78
+ if (error) {
79
+ console.error('登入失敗:', error);
80
+ return;
81
+ }
82
+
83
+ console.log('登入成功! 取得的資料:', data);
84
+ // 您可以在這裡處理登入成功後的邏輯,例如儲存 JWT token
85
+ if (data && data.token) {
86
+ localStorage.setItem('jwt_token', data.token);
87
+ console.log('JWT Token 已儲存到 localStorage。');
88
+ }
89
+
90
+ } catch (err) {
91
+ console.error('執行登入時發生意外錯誤:', err);
92
+ }
93
+ }
94
+
95
+ ```
96
+
97
+ ## Usage with Frameworks
98
+
99
+ This SDK is framework-agnostic. The Quick Start example uses standard JavaScript (`async/await`) that works in any modern environment. Here’s how you might integrate it into popular frameworks.
100
+
101
+ ### React Example
102
+
103
+ In a React component, you can use the `useEffect` hook to fetch data when the component mounts.
104
+
105
+ ```jsx
106
+ import React, { useState, useEffect } from 'react';
107
+ import cga from '@codegenapps/frontend-sdk';
108
+
109
+ // Initialize the SDK once in your app's entry point (e.g., index.js)
110
+ // await cga.init({ ... });
111
+
112
+ function DocumentsList() {
113
+ const [documents, setDocuments] = useState([]);
114
+ const [error, setError] = useState(null);
115
+ const [isLoading, setIsLoading] = useState(true);
116
+
117
+ useEffect(() => {
118
+ async function getDocuments() {
119
+ const { data, error } = await cga
120
+ .from('documents')
121
+ .select('id, title')
122
+ .eq('owner_id', 1)
123
+ .run();
124
+
125
+ if (error) {
126
+ setError(error);
127
+ } else {
128
+ setDocuments(data);
129
+ }
130
+ setIsLoading(false);
131
+ }
132
+
133
+ getDocuments();
134
+ }, []); // The empty dependency array ensures this runs once on mount
135
+
136
+ if (isLoading) return <div>Loading...</div>;
137
+ if (error) return <div>Error: {error.message}</div>;
138
+
139
+ return (
140
+ <ul>
141
+ {documents.map(doc => (
142
+ <li key={doc.id}>{doc.title}</li>
143
+ ))}
144
+ </ul>
145
+ );
146
+ }
147
+ ```
148
+
149
+ ### Vue.js Example
150
+
151
+ In a Vue component (using Composition API), you can use the `onMounted` hook.
152
+
153
+ ```vue
154
+ <script setup>
155
+ import { ref, onMounted } from 'vue';
156
+ import cga from '@codegenapps/frontend-sdk';
157
+
158
+ // Initialize the SDK once in your app's entry point (e.g., main.js)
159
+ // await cga.init({ ... });
160
+
161
+ const documents = ref([]);
162
+ const error = ref(null);
163
+ const isLoading = ref(true);
164
+
165
+ onMounted(async () => {
166
+ const { data, error: fetchError } = await cga
167
+ .from('documents')
168
+ .select('id, title')
169
+ .eq('owner_id', 1)
170
+ .run();
171
+
172
+ if (fetchError) {
173
+ error.value = fetchError;
174
+ } else {
175
+ documents.value = data;
176
+ }
177
+ isLoading.value = false;
178
+ });
179
+ </script>
180
+
181
+ <template>
182
+ <div v-if="isLoading">Loading...</div>
183
+ <div v-else-if="error">Error: {{ error.message }}</div>
184
+ <ul v-else>
185
+ <li v-for="doc in documents" :key="doc.id">
186
+ {{ doc.title }}
187
+ </li>
188
+ </ul>
189
+ </template>
64
190
  ```
65
191
 
66
192
  ## API
@@ -115,6 +241,47 @@ Example: `cga.from('daily_active_user').byPk({ activity_date: '...', user_id: 1,
115
241
 
116
242
  Executes the query and returns a `Promise` that resolves to `{ data, error }`. **All query chains must end with `.run()`.**
117
243
 
244
+ ### Customizing Requests
245
+
246
+ While the query builder provides methods for common operations, you can further customize requests by passing an `options` object to the action methods (`select`, `insert`, `update`, `delete`).
247
+
248
+ #### Adding Custom Headers
249
+
250
+ You can add or override headers for a specific request.
251
+
252
+ ```javascript
253
+ const { data, error } = await cga
254
+ .from('documents')
255
+ .select('id, title', { // <-- Pass options here
256
+ headers: {
257
+ 'X-Request-ID': 'custom-request-12345'
258
+ }
259
+ })
260
+ .run();
261
+ ```
262
+
263
+ #### Adding Custom Query Parameters
264
+
265
+ For special query parameters not covered by the built-in filter methods, you can use `axiosConfig.params`. These will be merged with the parameters generated by the builder.
266
+
267
+ ```javascript
268
+ const { data, error } = await cga
269
+ .from('documents')
270
+ .select('id, title', { // <-- Pass options here
271
+ axiosConfig: {
272
+ params: {
273
+ '_cache': false,
274
+ 'apiVersion': '2.1'
275
+ }
276
+ }
277
+ })
278
+ .eq('owner_id', 1) // Builder params are still used
279
+ .run();
280
+
281
+ // The above request will be sent to a URL like:
282
+ // /api/documents?_cache=false&apiVersion=2.1&filter=owner_id,eq,1
283
+ ```
284
+
118
285
  ## License
119
286
 
120
- MIT
287
+ MIT
@@ -54,11 +54,11 @@ export declare class CgaClient {
54
54
  get auth(): {
55
55
  /**
56
56
  * Logs in a user.
57
- * @param username The user's username.
57
+ * @param account The user's username.
58
58
  * @param password The user's password.
59
59
  * @param apiKey The API key required for login.
60
60
  */
61
- login(username: string, password: string, apiKey: string): Promise<{
61
+ login(account: string, password: string, apiKey: string): Promise<{
62
62
  data: any;
63
63
  error: null;
64
64
  } | {
package/dist/index.esm.js CHANGED
@@ -6366,15 +6366,15 @@ class CgaClient {
6366
6366
  return {
6367
6367
  /**
6368
6368
  * Logs in a user.
6369
- * @param username The user's username.
6369
+ * @param account The user's username.
6370
6370
  * @param password The user's password.
6371
6371
  * @param apiKey The API key required for login.
6372
6372
  */
6373
- login(username, password, apiKey) {
6373
+ login(account, password, apiKey) {
6374
6374
  return __awaiter(this, void 0, void 0, function* () {
6375
6375
  var _a;
6376
6376
  try {
6377
- const response = yield httpClient.post('/auth/login', { username, password }, { headers: { 'X-API-KEY': apiKey } });
6377
+ const response = yield httpClient.post('/auth/login', { account, password }, { headers: { 'X-API-KEY': apiKey } });
6378
6378
  return { data: response.data.data, error: null };
6379
6379
  }
6380
6380
  catch (error) {