stadata-js 0.4.0 → 2.0.0

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
@@ -2,317 +2,166 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/stadata-js.svg)](https://www.npmjs.com/package/stadata-js)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![Docs](https://img.shields.io/badge/docs-ipds--59.github.io-blue)](https://ipds-59.github.io/stadata_js/)
5
6
 
6
- Official TypeScript/JavaScript SDK for BPS (Badan Pusat Statistik) WebAPI - Seamlessly access Indonesia's Central Bureau of Statistics data through a comprehensive, type-safe client library.
7
+ Official TypeScript/JavaScript SDK for BPS (Badan Pusat Statistik) WebAPI Seamlessly access Indonesia's Central Bureau of Statistics data through a comprehensive, type-safe client library.
7
8
 
8
9
  ## Overview
9
10
 
10
11
  The STADATA JS SDK provides TypeScript/JavaScript developers with streamlined access to Indonesia's statistical data through the official BPS WebAPI. Create data-driven applications featuring demographic, economic, and socio-economic information from Indonesia's most authoritative statistical source.
11
12
 
12
- This toolkit facilitates seamless integration with BPS data sources, eliminating the need for manual downloads from the BPS website. Access publications, press releases, static/dynamic tables, infographics, census datasets, and much more through a clean, modern API.
13
-
14
13
  ## Features
15
14
 
16
- - **Full TypeScript Support** - Complete type definitions for all API endpoints with IntelliSense support
17
- - **Clean Architecture** - Follows Clean Architecture principles with clear separation of concerns
18
- - **Result Pattern** - Uses neverthrow library for elegant, functional error handling
19
- - **Dependency Injection** - Built-in DI container for flexible, testable architecture
20
- - **Request Cancellation** - Support for cancelling ongoing requests to optimize performance
21
- - **Interceptors** - Extensible request/response interceptor system for custom middleware
22
- - **Logging** - Configurable logging system with multiple log levels for debugging
23
- - **Immutable Entities** - All domain entities are immutable for predictable behavior
24
- - **Pagination Support** - Built-in pagination handling for all list endpoints
25
- - **Modern JavaScript** - Built for modern ES6+ environments with CommonJS and ESM support
15
+ - **Functional Composable API** `createStadataClient()` + `use*()` composables, idiomatic TypeScript
16
+ - **Full TypeScript Support** Complete type definitions with IntelliSense support
17
+ - **Result Pattern** Uses `neverthrow` for elegant, type-safe error handling
18
+ - **Tree-shakeable** Only bundle what you use
19
+ - **Pagination Support** — Built-in pagination handling for all list endpoints
20
+ - **Request Cancellation** Cancel ongoing requests to optimize performance
21
+ - **Immutable Entities** Predictable, safe domain entities
26
22
 
27
23
  ## Requirements
28
24
 
29
25
  - Node.js >= 16.0.0
30
- - Valid API key from BPS WebAPI platform
26
+ - Valid API key from [BPS WebAPI platform](https://webapi.bps.go.id/)
31
27
 
32
28
  ## Installation
33
29
 
34
30
  ```bash
31
+ # npm
35
32
  npm install stadata-js
36
- ```
37
33
 
38
- or using yarn:
34
+ # pnpm
35
+ pnpm add stadata-js
39
36
 
40
- ```bash
37
+ # yarn
41
38
  yarn add stadata-js
42
39
  ```
43
40
 
44
- or using pnpm:
45
-
46
- ```bash
47
- pnpm add stadata-js
48
- ```
49
-
50
41
  ## Quick Start
51
42
 
52
43
  ```typescript
53
- import { StadataJS, DataLanguage } from 'stadata-js';
44
+ import { initStadata, usePublications, useDomains, DataLanguage, DomainType } from 'stadata-js'
54
45
 
55
- // Initialize the SDK with your API key
56
- await StadataJS.init({
57
- apiKey: 'your-api-key-here',
58
- debug: false, // Enable debug logging if needed
59
- });
46
+ // 1. Initialize once at app entry point
47
+ initStadata({ apiKey: 'your-api-key-here' })
60
48
 
61
- // Get the SDK instance
62
- const stadata = StadataJS.instance;
49
+ // 2. Use composables anywhere — no client reference needed
50
+ const { fetchPublicationList, fetchPublicationDetail } = usePublications()
51
+ const { fetchDomainList } = useDomains()
63
52
 
64
- // Fetch all domains with pagination
65
- const domainsResult = await stadata.list.domains({
66
- lang: DataLanguage.EN,
53
+ // 3. Fetch data
54
+ const result = await fetchPublicationList({
55
+ domain: '7200',
56
+ lang: DataLanguage.ID,
67
57
  page: 1,
68
58
  perPage: 10,
69
- });
70
-
71
- // Handle the result using pattern matching
72
- domainsResult.match(
73
- (listResult) => {
74
- console.log('Domains:', listResult.data);
75
- console.log('Total:', listResult.pagination.total);
76
- console.log('Current Page:', listResult.pagination.page);
77
- },
78
- (error) => {
79
- console.error('Error:', error.message);
80
- }
81
- );
82
-
83
- // Fetch a specific domain by ID
84
- const domainResult = await stadata.view.domain({
85
- id: '7315',
86
- lang: DataLanguage.ID,
87
- });
88
-
89
- domainResult.match(
90
- (domain) => {
91
- console.log('Domain Name:', domain.name);
92
- console.log('Domain URL:', domain.url);
93
- },
94
- (error) => {
95
- console.error('Error:', error.message);
96
- }
97
- );
98
- ```
99
-
100
- ## Available Features
101
-
102
- ### ✅ Fully Implemented
103
-
104
- The SDK currently supports the following BPS data categories:
59
+ })
105
60
 
106
- 1. **Domains** - Statistical domain information
107
- 2. **Publications** - Statistical publications and reports
108
- 3. **Infographics** - Visual statistical representations
109
- 4. **News** - Latest statistical news
110
- 5. **News Categories** - News categorization
111
- 6. **Press Releases** - Official press releases
112
- 7. **Static Tables** - Pre-formatted statistical tables
113
- 8. **Subjects** - Statistical subjects
114
- 9. **Subject Categories** - Subject categorization
115
- 10. **Strategic Indicators** - Key economic indicators
116
- 11. **Variables** - Statistical variables
117
- 12. **Units** - Measurement units
118
- 13. **Periods** - Time periods
119
- 14. **Derived Variables** - Calculated statistical variables
120
- 15. **Derived Periods** - Calculated time periods
121
- 16. **Statistic Classifications** - Statistical classification systems
122
- 17. **Census** - Census data
123
- 18. **Dynamic Tables** - Interactive statistical tables
124
- 19. **Foreign Trade** - International trade statistics
125
-
126
- ### 🚧 Under Development
127
-
128
- The following features are planned for future releases:
129
-
130
- - **Glossary** - Statistical terminology
131
- - **SDG Indicators** - Sustainable Development Goals indicators
132
- - **Inflation** - Consumer price index data
133
- - **Exchange Rates** - Foreign currency exchange rates
134
-
135
- ## Usage Examples
136
-
137
- ### Fetching Publications
138
-
139
- ```typescript
140
- // Get all publications
141
- const publicationsResult = await stadata.list.publications({
142
- lang: DataLanguage.ID,
143
- domain: '7315',
144
- page: 1,
145
- perPage: 20,
146
- });
147
-
148
- publicationsResult.match(
149
- (result) => {
150
- result.data.forEach((publication) => {
151
- console.log(publication.title);
152
- console.log(publication.issn);
153
- console.log(publication.cover);
154
- });
61
+ result.match(
62
+ ({ data, pagination }) => {
63
+ console.log(`Total: ${pagination.total}`)
64
+ data.forEach(pub => console.log(pub.title))
155
65
  },
156
- (error) => console.error(error.message)
157
- );
66
+ (error) => console.error('Error:', error.message)
67
+ )
158
68
  ```
159
69
 
160
- ### Fetching Static Tables
161
-
162
- ```typescript
163
- // Get static tables with filters
164
- const tablesResult = await stadata.list.staticTables({
165
- lang: DataLanguage.EN,
166
- domain: '7315',
167
- page: 1,
168
- perPage: 15,
169
- });
170
-
171
- tablesResult.match(
172
- (result) => {
173
- result.data.forEach((table) => {
174
- console.log(table.title);
175
- console.log(table.subjectId);
176
- console.log(table.table);
177
- });
178
- },
179
- (error) => console.error(error.message)
180
- );
181
- ```
182
-
183
- ### Fetching Foreign Trade Data
70
+ ## API Reference
184
71
 
185
- ```typescript
186
- // Get trade data
187
- const tradeResult = await stadata.list.trades({
188
- lang: DataLanguage.ID,
189
- page: 1,
190
- perPage: 10,
191
- });
192
-
193
- tradeResult.match(
194
- (result) => {
195
- result.data.forEach((trade) => {
196
- console.log(trade.title);
197
- console.log(trade.period);
198
- console.log(trade.hsLevel);
199
- });
200
- },
201
- (error) => console.error(error.message)
202
- );
203
- ```
72
+ Full documentation: **[ipds-59.github.io/stadata_js](https://ipds-59.github.io/stadata_js/)**
73
+
74
+ ### Available Composables
75
+
76
+ | Composable | Functions |
77
+ |-----------|-----------|
78
+ | `stadata.useDomains()` | `fetchDomainList` |
79
+ | `stadata.usePublications()` | `fetchPublicationList`, `fetchPublicationDetail` |
80
+ | `stadata.usePressReleases()` | `fetchPressReleaseList`, `fetchPressReleaseDetail` |
81
+ | `stadata.useStaticTables()` | `fetchStaticTableList`, `fetchStaticTableDetail` |
82
+ | `stadata.useDynamicTables()` | `fetchDynamicTableList` |
83
+ | `stadata.useInfographics()` | `fetchInfographicList` |
84
+ | `stadata.useNews()` | `fetchNewsList`, `fetchNewsDetail` |
85
+ | `stadata.useNewsCategories()` | `fetchNewsCategoryList` |
86
+ | `stadata.useVariables()` | `fetchVariableList`, `fetchVariableDetail` |
87
+ | `stadata.useVerticalVariables()` | `fetchVerticalVariableList` |
88
+ | `stadata.useDerivedVariables()` | `fetchDerivedVariableList` |
89
+ | `stadata.useSubjects()` | `fetchSubjectList`, `fetchSubjectDetail` |
90
+ | `stadata.useSubjectCategories()` | `fetchSubjectCategoryList` |
91
+ | `stadata.useUnits()` | `fetchUnitList`, `fetchUnitDetail` |
92
+ | `stadata.usePeriods()` | `fetchPeriodList` |
93
+ | `stadata.useDerivedPeriods()` | `fetchDerivedPeriodList` |
94
+ | `stadata.useStrategicIndicators()` | `fetchStrategicIndicatorList`, `fetchStrategicIndicatorDetail` |
95
+ | `stadata.useStatisticClassifications()` | `fetchStatisticClassificationList`, `fetchStatisticClassificationDetail` |
96
+ | `stadata.useCensus()` | `fetchCensusList` |
97
+ | `stadata.useTrade()` | `fetchTradeData` |
204
98
 
205
99
  ### Error Handling
206
100
 
207
- The SDK uses the Result pattern from the `neverthrow` library for elegant error handling:
101
+ All functions return `Result<T, ApiFailure>` from [neverthrow](https://github.com/supermacro/neverthrow):
208
102
 
209
103
  ```typescript
210
- const result = await stadata.list.domains({
211
- lang: DataLanguage.EN,
212
- });
104
+ const result = await fetchPublicationList({ domain: '7200', lang: DataLanguage.ID })
213
105
 
214
- // Pattern matching approach
106
+ // Option 1: match
215
107
  result.match(
216
- (success) => {
217
- // Handle success case
218
- console.log('Data:', success.data);
219
- },
220
- (error) => {
221
- // Handle error case
222
- console.error('Error occurred:', error.message);
223
- }
224
- );
108
+ ({ data, pagination }) => console.log(data),
109
+ (error) => console.error(error.message)
110
+ )
225
111
 
226
- // isOk/isErr approach
112
+ // Option 2: guard check
227
113
  if (result.isOk()) {
228
- const data = result.value;
229
- console.log('Success:', data);
230
- } else {
231
- const error = result.error;
232
- console.error('Failed:', error);
114
+ const { data, pagination } = result.value
233
115
  }
234
- ```
235
-
236
- ## API Reference
237
-
238
- ### StadataJS
239
-
240
- Main SDK class for initialization and access to all features.
241
-
242
- #### Methods
243
116
 
244
- - `StadataJS.init(config: ApiConfig): Promise<void>` - Initialize the SDK with configuration
245
- - `StadataJS.instance: StadataJS` - Get the singleton SDK instance
246
-
247
- ### Configuration
248
-
249
- ```typescript
250
- interface ApiConfig {
251
- apiKey: string; // Your BPS WebAPI key (required)
252
- debug?: boolean; // Enable debug logging (default: false)
253
- baseUrl?: string; // Custom API base URL (optional)
117
+ if (result.isErr()) {
118
+ console.error(result.error.message)
254
119
  }
255
120
  ```
256
121
 
257
- ### Data Language
122
+ ## Configuration
258
123
 
259
124
  ```typescript
260
- enum DataLanguage {
261
- ID = 'ind', // Indonesian
262
- EN = 'eng', // English
263
- }
125
+ const stadata = createStadataClient({
126
+ apiKey: 'your-api-key', // required
127
+ timeout: 15000, // optional, ms (default: 30000)
128
+ debug: true, // optional, enable debug logging
129
+ baseURL: 'https://...', // optional, custom base URL
130
+ })
264
131
  ```
265
132
 
266
- ## Architecture
267
-
268
- The SDK follows Clean Architecture principles with clear separation between:
133
+ ## Migration from v1
269
134
 
270
- - **Domain Layer** - Business entities and use cases
271
- - **Data Layer** - Repository implementations and data sources
272
- - **Core Layer** - Base classes, utilities, and infrastructure
273
- - **API Layer** - Public-facing SDK interface
135
+ **v1 (deprecated):**
136
+ ```typescript
137
+ await StadataJS.init({ apiKey: 'key' })
138
+ const stadata = StadataJS.instance
139
+ const result = await stadata.list.publications({ domain: '7200', lang: DataLanguage.ID })
140
+ ```
274
141
 
275
- This architecture ensures:
276
- - High testability
277
- - Loose coupling between components
278
- - Easy maintenance and extensibility
279
- - Clear separation of concerns
142
+ **v2:**
143
+ ```typescript
144
+ // Entry point
145
+ initStadata({ apiKey: 'key' })
280
146
 
281
- ## Contributing
147
+ // Anywhere in app
148
+ const { fetchPublicationList } = usePublications()
149
+ const result = await fetchPublicationList({ domain: '7200', lang: DataLanguage.ID })
150
+ ```
282
151
 
283
- We welcome contributions! Whether you're fixing bugs, improving documentation, adding tests, or implementing new features, your help is appreciated.
152
+ > `StadataJS` class is kept as `@deprecated` in v2 and will be removed in v3.
284
153
 
285
- ### How to Contribute
154
+ ## Advanced: Multiple Clients
286
155
 
287
- 1. Fork the repository
288
- 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
289
- 3. Commit your changes using conventional commits (`git commit -m 'feat: add amazing feature'`)
290
- 4. Push to the branch (`git push origin feature/amazing-feature`)
291
- 5. Open a Pull Request to the `develop` branch
156
+ If you need multiple clients (e.g. different API keys), use `createStadataClient` directly:
292
157
 
293
- ### Contribution Areas
158
+ ```typescript
159
+ import { createStadataClient, usePublications } from 'stadata-js'
294
160
 
295
- - **Bug Reports** - Report issues you encounter
296
- - **Feature Requests** - Suggest new capabilities
297
- - **Documentation** - Improve guides and examples
298
- - **Testing** - Add or improve test coverage
299
- - **Code** - Implement new features or fix bugs
161
+ const client = createStadataClient({ apiKey: 'other-key' })
162
+ const { fetchPublicationList } = usePublications(client) // explicit client
163
+ ```
300
164
 
301
165
  ## License
302
166
 
303
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
304
-
305
- ## Links
306
-
307
- - [npm Package](https://www.npmjs.com/package/stadata-js)
308
- - [GitHub Repository](https://github.com/IPDS-59/stadata_js)
309
- - [Issue Tracker](https://github.com/IPDS-59/stadata_js/issues)
310
- - [BPS Website](https://www.bps.go.id)
311
-
312
- ## Acknowledgments
313
-
314
- This SDK is an unofficial community project and is not affiliated with or endorsed by BPS (Badan Pusat Statistik). All data accessed through this SDK is provided by BPS through their official WebAPI.
315
-
316
- ---
317
-
318
- Made with ❤️ for the Indonesian developer community
167
+ MIT © [IPDS-59](https://github.com/IPDS-59)