@dcc-bs/communication.bs.js 0.0.2 → 0.0.4

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.
Files changed (3) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +242 -4
  3. package/package.json +8 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Data Competence Center Basel-Stadt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,15 +1,253 @@
1
1
  # communication.bs.js
2
2
 
3
- To install dependencies:
3
+ A TypeScript library for type-safe API communication with built-in error handling, schema validation, and Vue composables. Designed for modern web applications that require robust HTTP request handling with automatic response parsing and validation.
4
+
5
+ This library expects the API to follow a consistent error response format to leverage its full capabilities. The error responses should include fields such as `errorId`, `statusCode`, and an optional `debugMessage` to ensure seamless integration with the library's error handling mechanisms.
6
+ ```json
7
+ {
8
+ "errorId": "string", // Unique identifier for the error type
9
+ "statusCode": 400, // HTTP status code associated with the error
10
+ "debugMessage": "string" // Optional detailed debug message for developers
11
+ }
12
+ ```
13
+
14
+ ![GitHub License](https://img.shields.io/github/license/DCC-BS/communication.bs.js) [![Checked with Biome](https://img.shields.io/badge/Checked_with-Biome-60a5fa?style=flat&logo=biome)](https://biomejs.dev) ![NPM Version](https://img.shields.io/npm/v/%40dcc-bs%2Fcommunication.bs.js)
15
+
16
+
17
+ ## Features
18
+
19
+ - **Type-Safe API Requests**: Full TypeScript support with type inference
20
+ - **Schema Validation**: Built-in Zod schema validation for API responses
21
+ - **Error Handling**: Standardized API error responses with custom error types
22
+ - **Streaming Support**: Handle streaming API responses with ease
23
+ - **Vue Composables**: Ready-to-use Vue 3 composables for reactive API calls
24
+ - **Multiple Response Types**: Support for JSON, text, and streaming responses
25
+ - **Abort Support**: Request cancellation with AbortController integration
26
+ - **FormData Support**: Automatic handling of multipart/form-data requests
27
+
28
+ ## Technology Stack
29
+
30
+ - **Runtime**: [Bun](https://bun.sh/)
31
+ - **Build Tool**: [Vite](https://vitejs.dev/)
32
+ - **Testing**: [Vitest](https://vitest.dev/)
33
+ - **Schema Validation**: [Zod](https://zod.dev/)
34
+ - **Framework Support**: [Vue 3](https://vuejs.org/) (optional)
35
+ - **Code Quality**: [Biome](https://biomejs.dev/)
36
+
37
+ ## Installation
38
+
39
+ Install the package using your preferred package manager:
40
+
41
+ ```bash
42
+ # Using bun
43
+ bun add @dcc-bs/communication.bs.js
44
+
45
+ # Using npm
46
+ npm install @dcc-bs/communication.bs.js
47
+
48
+ # Using pnpm
49
+ pnpm add @dcc-bs/communication.bs.js
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ ### Basic API Fetch
55
+
56
+ ```typescript
57
+ import { apiFetch, isApiError } from '@dcc-bs/communication.bs.js';
58
+
59
+ // Simple API call
60
+ const response = await apiFetch<{ message: string }>('/api/hello');
61
+
62
+ // the resposne is of type { message: string } | ApiError
63
+ // the isApiError function is a type guard so we can narrow the type
64
+ if (isApiError(response)) {
65
+ console.error('API Error:', response.errorId, response.statusCode);
66
+ } else {
67
+ console.log('Success:', response.message);
68
+ }
69
+ ```
70
+
71
+ ### With Zod Schema Validation
72
+
73
+ ```typescript
74
+ import { apiFetch } from '@dcc-bs/communication.bs.js';
75
+ import { z } from 'zod';
76
+
77
+ const UserSchema = z.object({
78
+ id: z.number(),
79
+ name: z.string(),
80
+ email: z.email(),
81
+ });
82
+
83
+ const response = await apiFetch('/api/user/1', {
84
+ schema: UserSchema,
85
+ });
86
+
87
+ if (!isApiError(response)) {
88
+ // response is fully typed as z.infer<typeof UserSchema>
89
+ console.log(response.email);
90
+ }
91
+ ```
92
+
93
+ ### Vue Composables
94
+ The composables provide a reactive way similar to [`useFetch`](https://nuxt.com/docs/4.x/api/composables/use-fetch) to handle API requests in Vue 3 applications.
95
+
96
+ ```typescript
97
+ import { useApiFetch, useApiFetchWithSchema } from '@dcc-bs/communication.bs.js';
98
+ import { z } from 'zod';
99
+
100
+ // Basic composable
101
+ const { data, error, pending } = useApiFetch<User>('/api/user/1');
102
+
103
+ // data is of type Ref<User | undefined>
104
+ // error is of type Ref<ApiErrorResponse | undefined>
105
+ // pending is of type Ref<boolean>
106
+
107
+ // With schema validation
108
+ const UserSchema = z.object({
109
+ id: z.number(),
110
+ name: z.string(),
111
+ });
112
+
113
+ const { data, error, pending } = useApiFetchWithSchema('/api/user/1', {
114
+ schema: UserSchema,
115
+ });
116
+ ```
117
+
118
+ ### Streaming API Responses
119
+
120
+ ```typescript
121
+ import { apiStreamFetch } from '@dcc-bs/communication.bs.js';
122
+
123
+ const response = apiStreamFetch('/api/stream', {
124
+ method: 'POST',
125
+ body: { prompt: 'Generate text...' },
126
+ });
127
+
128
+ if(isApiError(response)) {
129
+ throw new Error(response.debugMessage);
130
+ }
131
+
132
+ const reader = response.getReader();
133
+ const decoder = new TextDecoder();
134
+
135
+ while (true) {
136
+ const { done, value } = await reader.read();
137
+ if (done) break;
138
+ const chunk = decoder.decode(value, {
139
+ stream: true,
140
+ });
141
+ console.log('Received chunk:', chunk);
142
+ }
143
+ ```
144
+
145
+ ### Fetch streaming responses with async iteration
146
+
147
+ ```typescript
148
+ import { apiFetchMany, apiFetchTextMany } from '@dcc-bs/communication.bs.js';
149
+ import { z } from 'zod';
150
+
151
+ const UserSchema = z.object({
152
+ id: z.number(),
153
+ name: z.string(),
154
+ });
155
+
156
+ // Fetch multiple JSON endpoints
157
+ const results = await apiFetchMany("/api/users",
158
+ {
159
+ method: "GET",
160
+ schema: z.array(UserSchema),
161
+ });
162
+
163
+ await for(const user of results) {
164
+ console.log(user.id);
165
+ console.log(user.name);
166
+ }
167
+
168
+ // Fetch multiple text endpoints
169
+ const textResults = await apiFetchTextMany("/api/content/1");
170
+
171
+ await for(const text of textResults) {
172
+ console.log(text);
173
+ }
174
+ ```
175
+
176
+ ## Development
177
+
178
+ ### Setup
179
+
180
+ Install dependencies:
4
181
 
5
182
  ```bash
6
183
  bun install
7
184
  ```
8
185
 
9
- To run:
186
+ ### Testing
187
+
188
+ Run tests with Vitest:
10
189
 
11
190
  ```bash
12
- bun run index.ts
191
+ # Run tests
192
+ bun run test
13
193
  ```
14
194
 
15
- This project was created using `bun init` in bun v1.2.9. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
195
+ ### Building
196
+
197
+ Build the library:
198
+
199
+ ```bash
200
+ bun run build
201
+ ```
202
+
203
+ This generates both ESM and UMD bundles in the `dist/` directory.
204
+
205
+ ### Linting & Formatting
206
+
207
+ Check and fix code issues with Biome:
208
+
209
+ ```bash
210
+ bun run check
211
+ ```
212
+
213
+ ## Project Structure
214
+
215
+ ```
216
+ src/
217
+ ├── apiFetch.ts # Core API fetch functions
218
+ ├── index.ts # Main entry point
219
+ ├── composables/ # Vue composables
220
+ │ ├── apiFetch.composable.ts
221
+ │ └── useApiFetchWithSchema.ts
222
+ └── models/ # TypeScript models
223
+ ├── api_error.ts
224
+ ├── api_error_response.ts
225
+ └── api_fetch_options.ts
226
+ tests/ # Test files
227
+ ├── apiFetch.test.ts
228
+ ├── apiFetchTextMany.test.ts
229
+ ├── apiStreamFetch.test.ts
230
+ └── isApiError.test.ts
231
+ ```
232
+
233
+ ## Error Handling
234
+
235
+ The library provides standardized error handling with predefined error types:
236
+
237
+ - `unexpected_error`: Unexpected API response format
238
+ - `fetch_failed`: Network or fetch operation failure
239
+ - `request_aborted`: Request was cancelled via AbortController
240
+
241
+ All errors follow the `ApiError` structure with:
242
+ - `errorId`: Unique error identifier
243
+ - `statusCode`: HTTP status code
244
+ - `debugMessage`: Optional debug information
245
+
246
+ ## License
247
+
248
+ [MIT](LICENSE) © Data Competence Center Basel-Stadt
249
+
250
+ <a href="https://www.bs.ch/schwerpunkte/daten/databs/schwerpunkte/datenwissenschaften-und-ki"><img src="https://github.com/DCC-BS/.github/blob/main/_imgs/databs_log.png?raw=true" alt="DCC Logo" width="200" /></a>
251
+
252
+ Datenwissenschaften und KI <br>
253
+ Developed with ❤️ by DCC - Data Competence Center
package/package.json CHANGED
@@ -1,25 +1,28 @@
1
1
  {
2
2
  "name": "@dcc-bs/communication.bs.js",
3
- "module": "./dist/communication.bs.js",
3
+ "module": "./dist/communication.bs.js.js",
4
4
  "main": "./dist/communication.bs.js.umd.js",
5
5
  "type": "module",
6
- "version": "0.0.2",
6
+ "version": "0.0.4",
7
7
  "types": "dist/communication.bs.d.ts",
8
8
  "declaration": true,
9
9
  "exports": {
10
10
  ".": {
11
- "import": "./dist/communication.bs.js",
11
+ "import": "./dist/communication.bs.js.js",
12
12
  "require": "./dist/communication.bs.js.umd.js"
13
13
  }
14
14
  },
15
- "files": ["./dist", "README.md"],
15
+ "files": [
16
+ "./dist",
17
+ "README.md"
18
+ ],
16
19
  "scripts": {
17
20
  "check": "biome check --write",
18
21
  "build": "vite build",
19
22
  "test": "vitest"
20
23
  },
21
24
  "devDependencies": {
22
- "@biomejs/biome": "2.2.4",
25
+ "@biomejs/biome": "2.3.7",
23
26
  "@types/bun": "latest",
24
27
  "vite-plugin-dts": "^4.5.4",
25
28
  "vitest": "^4.0.13"