@tanglemedia/svelte-starter-directus-api 0.1.4 → 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2024 Tangle Media
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,262 @@
1
1
  # Directus-api
2
2
 
3
+ <p align="center" style="align: center;">
4
+ <a href="https://npm.im/@tanglemedia/svelte-starter-directus-api">
5
+ <img src="https://img.shields.io/badge/TypeScript-blue?style=flat-square" alt="TypeScript" />
6
+ </a>
7
+
8
+ <img alt="NPM Version" src="https://img.shields.io/npm/v/%40tanglemedia%2Fsvelte-starter-directus-api">
9
+
10
+ <a href="https://bitbucket.org/tanglemediainc/svelte-starter/src/master/packages/core/">
11
+ <img alt="Repo Bitbucket" src="https://img.shields.io/badge/repo-bitbucket-blue">
12
+ </a>
13
+
14
+ <img alt="Bitbucket open pull requests " src="https://img.shields.io/bitbucket/pr/tanglemediainc/svelte-starter">
15
+
16
+ <a href="https://choosealicense.com/licenses/mit/">
17
+ <img alt="NPM License" src="https://img.shields.io/npm/l/%40tanglemedia%2Fsvelte-starter-directus-api">
18
+ </a>
19
+ </p>
20
+
3
21
  _This package is experimental and is meant for internal use only._
22
+
23
+ ## Application
24
+
25
+ This is the entry point for initialing the application.
26
+
27
+ ```typescript
28
+ // boot/index.ts
29
+ import { createApplication } from '@tanglemedia/svelte-starter-core';
30
+ import { registerDirectusProvider } from '@tanglemedia/svelte-starter-directus-api';
31
+
32
+ const configuredApp = createApplication({
33
+ provider: {
34
+ // This register the directus provider, i.e, creates a directus service
35
+ register: [registerDirectusProvider()]
36
+ }
37
+ });
38
+
39
+ export default configuredApp;
40
+
41
+ export const { configureService, getConfiguration, application, provideConfig } = configuredApp;
42
+ ```
43
+
44
+ ## Configuration file
45
+
46
+ This is the entry point for your Directus adapter configs, inside the **api.yml** file.
47
+
48
+ ```yml
49
+ # This defines your default adapter
50
+ default: 'directus'
51
+
52
+ adapters:
53
+ # These are each custom adapters you can set, the key name can be what ever you want
54
+ directus-client:
55
+ adapter: 'directus'
56
+ configuration:
57
+ host: $PUBLIC_DIRECTUS_HOST
58
+ protocol: $PUBLIC_DIRECTUS_PROTOCOL
59
+ auth:
60
+ mode: 'json'
61
+ config:
62
+ storage: 'localStorage'
63
+ autoRefresh: true
64
+ msRefreshBeforeExpires: 30000
65
+ credentials: 'include'
66
+
67
+ directus-auth:
68
+ adapter: 'directus'
69
+ configuration:
70
+ host: $PUBLIC_DIRECTUS_HOST
71
+ protocol: $PUBLIC_DIRECTUS_PROTOCOL
72
+ auth:
73
+ mode: 'json'
74
+ config:
75
+ storage: 'localStorage'
76
+ autoRefresh: true
77
+ msRefreshBeforeExpires: 30000
78
+ credentials: 'include'
79
+
80
+ directus-static:
81
+ adapter: 'directus'
82
+ configuration:
83
+ host: $PUBLIC_DIRECTUS_HOST
84
+ protocol: $PUBLIC_DIRECTUS_PROTOCOL
85
+ staticToken: $PUBLIC_DIRECTUS_ACCESS_TOKEN
86
+ ```
87
+
88
+ ## Services
89
+
90
+ Services is a simple abstraction layer that makes some assumptions around common api requests and responses. Sevices rely on an underlying adapter which is responsible for transforming the request/response payloads and handling the actual requests to an api.
91
+ Once you have that you can create different services to handle different collections of your Directus project, here I am going to show three different services examples:
92
+
93
+ ```typescript
94
+ // DIRECTUS AUTH SERVICE
95
+ import { configureService } from '../../boot';
96
+ import { DirectusAuthServices } from '@tanglemedia/svelte-starter-directus-api';
97
+ import { createQuery, type Query, type QueryObserverOptions } from '@tanstack/svelte-query';
98
+
99
+ interface FilesInterface {
100
+ id: string;
101
+ }
102
+
103
+ const authService = configureService(DirectusAuthServices, {
104
+ path: '',
105
+ transform: (data) => data,
106
+ adapterKey: 'directus-auth'
107
+ });
108
+
109
+ // This is a specific service to have access to the base api functions, like find, create, update... that you get from the Core package, but also you get specific Auth functions like:
110
+ await authService.getToken();
111
+ // or
112
+ await authService.logout();
113
+ // or
114
+ await authService.getCurrentUser();
115
+ // or
116
+ await authService.updateCurrentUser();
117
+ // or
118
+ await authService.login(formValues.email, formValues.password);
119
+ // or
120
+ await authService.refresh();
121
+ // or
122
+ await authService.readFile(file);
123
+ ```
124
+
125
+ ```typescript
126
+ // DIRECTUS STATIC SERVICE
127
+ import { configureService } from '../../boot';
128
+ import { DirectusStaticServices } from '@tanglemedia/svelte-starter-directus-api';
129
+
130
+ const staticService = configureService(DirectusStaticServices, {
131
+ path: '',
132
+ transform: (data) => data,
133
+ adapterKey: 'directus-static'
134
+ });
135
+
136
+ // This is a specific service to have access to the base api functions, like find, create, update... that you get from the Core package, but also you get specific Static functions that you need the static token from Directus:
137
+ await authService.createUser(userData);
138
+ ```
139
+
140
+ ```typescript
141
+ // DIRECTUS CLIENT SERVICE
142
+ import type { FormInterface, FormResultInterface } from '$lib/models/form';
143
+ import { createQuery, type Query, type QueryObserverOptions } from '@tanstack/svelte-query';
144
+ import { configureService } from '../../boot';
145
+ import { ServiceAbstract } from '@tanglemedia/svelte-starter-core';
146
+
147
+ class Forms extends ServiceAbstract {}
148
+ class FormResults extends ServiceAbstract {}
149
+
150
+ export type FormsQuery = Query<FormInterface>;
151
+ export type FormResultsQuery = Query<FormResultInterface>;
152
+
153
+ type CreateOpt = {
154
+ enabled?: QueryObserverOptions['enabled'];
155
+ };
156
+
157
+ export const formsServiceClient = configureService<FormInterface>(Forms, {
158
+ // path is the name of your collection in Directus
159
+ path: 'forms',
160
+ transform: (data) => data,
161
+ adapterKey: 'directus-client'
162
+ });
163
+
164
+ export default formsServiceClient;
165
+
166
+ // This is a specific service to have access to the base api functions, like find, create, update... that you get from the Core package, example:
167
+ form = await formsServiceClient
168
+ .findOne(params.id, { fields: ['name', 'description'] })
169
+ .then((res) => res.data);
170
+ ```
171
+
172
+ ## Breaking Changes
173
+
174
+ ### Migrating from 0.1.4 to 1.0.0
175
+
176
+ On this migration we removed completely some deprecated Service functions:
177
+
178
+ 1. ApiAuthDirectus
179
+ 2. ApiClientDirectus
180
+ 3. LoadDirectusApiProvider
181
+ 4. ApiStaticDirectus
182
+
183
+ These types of initializing **Auth**, **Static**, and **Client** Directus services won't work on new major version:
184
+
185
+ ```typescript
186
+ // LEGACY WAY - NOW DEPRECATED AND NOT SUPPORTED
187
+ import { ApiAuthDirectus } from '@tanglemedia/svelte-starter-directus-api';
188
+ import { getConfiguration } from '../boot';
189
+
190
+ let directus: ApiAuthDirectus;
191
+
192
+ const configApi = async () => {
193
+ const config = await getConfiguration();
194
+ const protocol: string = config.config(`api.adapters.directus.protocol`) || '';
195
+ const host: string = config.config(`api.adapters.directus.host`) || '';
196
+ const direcutsUrl = `${protocol}://${host}`.trim();
197
+ directus = new ApiAuthDirectus(direcutsUrl, 'json');
198
+ };
199
+
200
+ async function getDirectus() {
201
+ if (!directus) {
202
+ await configApi();
203
+ }
204
+ return directus;
205
+ }
206
+
207
+ export { getDirectus };
208
+
209
+ // CURRENT WAY
210
+ import { configureService } from '../../boot';
211
+ import { DirectusAuthServices } from '@tanglemedia/svelte-starter-directus-api';
212
+ import { createQuery, type Query, type QueryObserverOptions } from '@tanstack/svelte-query';
213
+
214
+ interface FilesInterface {
215
+ id: string;
216
+ }
217
+
218
+ const authService = configureService(DirectusAuthServices, {
219
+ path: '',
220
+ transform: (data) => data,
221
+ adapterKey: 'directus-auth'
222
+ });
223
+
224
+ export default authService;
225
+ ```
226
+
227
+ ```typescript
228
+ // LEGACY WAY - NOW DEPRECATED AND NOT SUPPORTED
229
+ import { getConfiguration } from '../boot';
230
+ import { LoadDirectusApiProvider } from '@tanglemedia/svelte-starter-directus-api';
231
+
232
+ const configApi = async () => {
233
+ const res = await getConfiguration();
234
+ return res;
235
+ };
236
+
237
+ const apiProvider = new LoadDirectusApiProvider(configApi, 'json');
238
+
239
+ export { apiProvider };
240
+
241
+ // CURRENT WAY
242
+ import type { FormInterface, FormResultInterface } from '$lib/models/form';
243
+ import { createQuery, type Query, type QueryObserverOptions } from '@tanstack/svelte-query';
244
+ import { configureService } from '../../boot';
245
+ import { ServiceAbstract } from '@tanglemedia/svelte-starter-core';
246
+
247
+ class Forms extends ServiceAbstract {}
248
+ class FormResults extends ServiceAbstract {}
249
+
250
+ export type FormsQuery = Query<FormInterface>;
251
+ export type FormResultsQuery = Query<FormResultInterface>;
252
+
253
+ type CreateOpt = {
254
+ enabled?: QueryObserverOptions['enabled'];
255
+ };
256
+
257
+ export const formsServiceClient = configureService<FormInterface>(Forms, {
258
+ path: 'forms',
259
+ transform: (data) => data,
260
+ adapterKey: 'directus-client'
261
+ });
262
+ ```
package/dist/index.d.ts CHANGED
@@ -1,7 +1,3 @@
1
- export * from './static.deprecated';
2
- export * from './client.deprecated';
3
- export * from './auth.deprecated';
4
- export * from './load-directus-api-povider.deprecated';
5
1
  export * from './provider/api-adapter.provider';
6
2
  export * from './provider/directus.factory';
7
3
  export * from './services/auth';
package/dist/index.js CHANGED
@@ -1,7 +1,3 @@
1
- export * from './static.deprecated';
2
- export * from './client.deprecated';
3
- export * from './auth.deprecated';
4
- export * from './load-directus-api-povider.deprecated';
5
1
  export * from './provider/api-adapter.provider';
6
2
  export * from './provider/directus.factory';
7
3
  export * from './services/auth';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanglemedia/svelte-starter-directus-api",
3
- "version": "0.1.4",
3
+ "version": "1.0.1",
4
4
  "main": "src/index.ts",
5
5
  "types": "src/index.ts",
6
6
  "description": "directus API wrapper for all the directus sdk functionality",
@@ -22,29 +22,29 @@
22
22
  }
23
23
  },
24
24
  "devDependencies": {
25
- "@sveltejs/adapter-auto": "^3.1.1",
26
- "@sveltejs/package": "^2.2.6",
27
- "@sveltejs/vite-plugin-svelte": "^3.0.2",
25
+ "@sveltejs/adapter-auto": "^3.2.0",
26
+ "@sveltejs/package": "^2.3.1",
27
+ "@sveltejs/vite-plugin-svelte": "^3.1.0",
28
28
  "@testing-library/jest-dom": "^6.4.2",
29
29
  "@testing-library/svelte": "^4.1.0",
30
- "@vitest/coverage-v8": "^1.2.2",
30
+ "@vitest/coverage-v8": "^1.5.0",
31
31
  "jsdom": "^24.0.0",
32
- "msw": "^2.2.0",
33
- "svelte": "^4.2.11",
34
- "svelte-check": "^3.6.4",
35
- "vite": "^5.1.3",
36
- "vitest": "^1.2.2",
37
- "eslint-config-custom": "0.0.0"
32
+ "msw": "^2.2.13",
33
+ "svelte": "^4.2.14",
34
+ "svelte-check": "^3.6.9",
35
+ "vite": "^5.2.9",
36
+ "vitest": "^1.5.0",
37
+ "@internal/eslint-config": "0.0.0"
38
38
  },
39
39
  "dependencies": {
40
- "@directus/sdk": "^15.0.1",
40
+ "@directus/sdk": "^15.1.0",
41
41
  "@types/js-cookie": "^3.0.6",
42
42
  "esm-env": "^1.0.0",
43
- "js-cookie": "^3.0.5",
44
- "@tanglemedia/svelte-starter-core": "0.1.0"
43
+ "js-cookie": "^3.0.5"
45
44
  },
46
45
  "peerDependencies": {
47
46
  "@sveltejs/kit": ">=2 <3",
47
+ "@tanglemedia/svelte-starter-core": ">=0.1.4",
48
48
  "svelte": ">=4 <5"
49
49
  },
50
50
  "scripts": {
package/src/index.ts CHANGED
@@ -1,8 +1,3 @@
1
- export * from './static.deprecated';
2
- export * from './client.deprecated';
3
- export * from './auth.deprecated';
4
- export * from './load-directus-api-povider.deprecated';
5
-
6
1
  export * from './provider/api-adapter.provider';
7
2
  export * from './provider/directus.factory';
8
3
 
@@ -1,16 +0,0 @@
1
- import type { DirectusClient, RestClient } from '@directus/sdk';
2
- declare class ApiAuthDirectus {
3
- private baseURL;
4
- private storageMode;
5
- private directus;
6
- constructor(baseURL: string, storageMode?: 'json' | 'cookie');
7
- private init;
8
- getConfig<T extends object>(): DirectusClient<T> & RestClient<object>;
9
- refresh<T>(): Promise<T>;
10
- getToken<T>(): Promise<T>;
11
- login<T>(email: string, password: string): Promise<T>;
12
- logout<T>(): Promise<T>;
13
- getCurrentUser<T>(fields?: string[] | null): Promise<T>;
14
- updateCurrentUser<T>(data: object): Promise<T>;
15
- }
16
- export { ApiAuthDirectus };
@@ -1,104 +0,0 @@
1
- import { authentication, createDirectus, readMe, refresh, rest, updateMe } from '@directus/sdk';
2
- import { AuthLocalStorage } from './storage/local-storage';
3
- const authenticationConfig = {
4
- storage: new AuthLocalStorage(),
5
- autoRefresh: true,
6
- msRefreshBeforeExpires: 30000,
7
- credentials: 'include'
8
- };
9
- class ApiAuthDirectus {
10
- baseURL;
11
- storageMode;
12
- directus;
13
- constructor(baseURL, storageMode = 'json') {
14
- this.baseURL = baseURL;
15
- this.storageMode = storageMode;
16
- this.init();
17
- }
18
- init() {
19
- try {
20
- if (this.storageMode === 'json') {
21
- this.directus = createDirectus(this.baseURL)
22
- .with(rest({ credentials: 'include' }))
23
- .with(authentication('json', authenticationConfig));
24
- }
25
- else {
26
- this.directus = createDirectus(this.baseURL)
27
- .with(authentication('cookie', { credentials: 'include' }))
28
- .with(rest({ credentials: 'include' }));
29
- }
30
- }
31
- catch (error) {
32
- console.error(`Error initializing Directus:`, error);
33
- throw error;
34
- }
35
- }
36
- getConfig() {
37
- return this.directus;
38
- }
39
- async refresh() {
40
- try {
41
- const response = await this.directus.request(refresh());
42
- return response;
43
- }
44
- catch (error) {
45
- console.error(`Error refreshing :`, error);
46
- throw error;
47
- }
48
- }
49
- async getToken() {
50
- try {
51
- const response = await this.directus.getToken();
52
- return response;
53
- }
54
- catch (error) {
55
- console.error(`Error refreshing :`, error);
56
- throw error;
57
- }
58
- }
59
- async login(email, password) {
60
- try {
61
- const response = await this.directus.login(email, password);
62
- return response;
63
- }
64
- catch (error) {
65
- console.error(`Error login :`, error);
66
- throw error;
67
- }
68
- }
69
- async logout() {
70
- try {
71
- const response = await this.directus.logout();
72
- return response;
73
- }
74
- catch (error) {
75
- console.error(`Error refreshing :`, error);
76
- throw error;
77
- }
78
- }
79
- async getCurrentUser(fields = null) {
80
- try {
81
- if (!this.getToken())
82
- await this.refresh();
83
- const response = await this.directus.request(readMe({ fields: fields ? fields : ['*', 'roles.*'] }));
84
- return response;
85
- }
86
- catch (error) {
87
- console.error(`Error refreshing :`, error);
88
- throw error;
89
- }
90
- }
91
- async updateCurrentUser(data) {
92
- try {
93
- if (!this.getToken())
94
- await this.refresh();
95
- const response = await this.directus.request(updateMe(data));
96
- return response;
97
- }
98
- catch (error) {
99
- console.error(`Error refreshing :`, error);
100
- throw error;
101
- }
102
- }
103
- }
104
- export { ApiAuthDirectus };
@@ -1,21 +0,0 @@
1
- import type { AnyObject, ApiAdapterInterface, ApiAdapterRequestConfig, BaseApiAdapterConfig } from '@tanglemedia/svelte-starter-core';
2
- type BaseApiMethods = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
3
- type ApiId = string | number;
4
- declare class ApiClientDirectus implements ApiAdapterInterface {
5
- private baseURL;
6
- private storageMode;
7
- private directus;
8
- constructor(baseURL: string, storageMode?: 'json' | 'cookie');
9
- private init;
10
- getConfig<T extends object>(configuration?: unknown): BaseApiAdapterConfig;
11
- request<T>(method: BaseApiMethods, url: string, query?: Record<string, unknown>): Promise<T>;
12
- find<T>(collection: string, query?: Record<string, unknown>): Promise<T>;
13
- findOne<T>(collection: string, key?: ApiId, query?: Record<string, unknown>): Promise<T>;
14
- aggregate<T>(collection: string, query?: Record<string, unknown>): Promise<T>;
15
- patch<T>(collection: string, key: ApiId, query?: Record<string, unknown>): Promise<T>;
16
- post<T>(collection: string, data: AnyObject, query?: Record<string, unknown>): Promise<T>;
17
- delete<T>(collection: string, key?: ApiId): Promise<T>;
18
- put<T>(collection: string, payload: AnyObject, config?: ApiAdapterRequestConfig, key?: ApiId): Promise<T>;
19
- upload<T>(path: string | undefined, data: FormData): Promise<T>;
20
- }
21
- export { ApiClientDirectus };
@@ -1,156 +0,0 @@
1
- import { aggregate, authentication, createDirectus, createItem, deleteItem, readItem, readItems, rest, updateItem, uploadFiles } from '@directus/sdk';
2
- import { AuthLocalStorage } from './storage/local-storage';
3
- const authenticationConfig = {
4
- storage: new AuthLocalStorage(),
5
- autoRefresh: true,
6
- msRefreshBeforeExpires: 30000,
7
- credentials: 'include'
8
- };
9
- class ApiClientDirectus {
10
- baseURL;
11
- storageMode;
12
- directus;
13
- constructor(baseURL, storageMode = 'json') {
14
- this.baseURL = baseURL;
15
- this.storageMode = storageMode;
16
- this.init();
17
- }
18
- init() {
19
- try {
20
- if (this.storageMode === 'json') {
21
- this.directus = createDirectus(this.baseURL)
22
- .with(rest({ credentials: 'include' }))
23
- .with(authentication('json', authenticationConfig));
24
- }
25
- else {
26
- this.directus = createDirectus(this.baseURL)
27
- .with(authentication('cookie', { credentials: 'include' }))
28
- .with(rest({ credentials: 'include' }));
29
- }
30
- }
31
- catch (error) {
32
- console.error(`Error initializing Directus:`, error);
33
- throw error;
34
- }
35
- }
36
- getConfig(configuration) {
37
- // return this.directus as DirectusClient<T> & RestClient<object>;
38
- const client = this.directus;
39
- // Add the 'configuration' property to the returned object
40
- const config = {
41
- configuration: configuration ?? {} // Use the provided configuration or an empty object if not provided
42
- };
43
- return Object.assign(client, config);
44
- }
45
- async request(method, url, query) {
46
- try {
47
- const response = await this.directus.request(() => {
48
- const params = JSON.stringify(query);
49
- return {
50
- path: `${url}?${params}`,
51
- method: method
52
- };
53
- });
54
- return response;
55
- }
56
- catch (error) {
57
- console.error(`Error request:`, error);
58
- throw error;
59
- }
60
- }
61
- async find(collection, query) {
62
- // console.log('in find');
63
- try {
64
- // console.log(`Find ${collection}`)
65
- const response = await this.directus.request(readItems(collection, query));
66
- return response;
67
- }
68
- catch (error) {
69
- console.error(`Error fetching all ${collection}:`, error);
70
- throw error;
71
- }
72
- }
73
- async findOne(collection, key, query) {
74
- try {
75
- const response = await this.directus.request(readItem(collection, key, query));
76
- return response;
77
- }
78
- catch (error) {
79
- console.error(`Error fetching ${collection}:`, error);
80
- throw error;
81
- }
82
- }
83
- async aggregate(collection, query) {
84
- try {
85
- const response = await this.directus.request(aggregate(collection, {
86
- aggregate: {
87
- count: 'id'
88
- },
89
- query
90
- }));
91
- return response;
92
- }
93
- catch (error) {
94
- console.error(`Error fetching total of ${collection}:`, error);
95
- throw error;
96
- }
97
- }
98
- async patch(collection, key, query) {
99
- try {
100
- const response = await this.directus.request(updateItem(collection, key, query));
101
- return response;
102
- }
103
- catch (error) {
104
- console.error(`Error updating all ${collection}:`, error);
105
- throw error;
106
- }
107
- }
108
- async post(collection, data, query) {
109
- try {
110
- const response = await this.directus.request(createItem(collection, data, query));
111
- return response;
112
- }
113
- catch (error) {
114
- console.error(`Error creating items ${collection}:`, error);
115
- throw error;
116
- }
117
- }
118
- async delete(collection, key) {
119
- try {
120
- const response = await this.directus.request(deleteItem(collection, key));
121
- return response;
122
- }
123
- catch (error) {
124
- console.error(`Error deleting items ${collection}:`, error);
125
- throw error;
126
- }
127
- }
128
- async put(collection, payload, config, key) {
129
- try {
130
- if (key) {
131
- const response = await this.directus.request(updateItem(collection, key, payload));
132
- return response;
133
- }
134
- else {
135
- console.error(`Error updating all ${collection}: no key specified`);
136
- throw new Error('No key specified');
137
- }
138
- }
139
- catch (error) {
140
- console.error(`Error updating all ${collection}:`, error);
141
- throw error;
142
- }
143
- }
144
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
145
- async upload(path = '', data) {
146
- try {
147
- const response = await this.directus.request(uploadFiles(data));
148
- return response;
149
- }
150
- catch (error) {
151
- console.error(`Error uploading file:`, error);
152
- throw error;
153
- }
154
- }
155
- }
156
- export { ApiClientDirectus };
@@ -1,11 +0,0 @@
1
- import { type ApiAdapterProviderInterface, type ApiAdapterInterface, type ApiAdapterRequestConfig, type BaseApiAdapterConfig, type Config, type ApiConfigSchema } from '@tanglemedia/svelte-starter-core';
2
- declare class LoadDirectusApiProvider implements ApiAdapterProviderInterface {
3
- private readonly configLoader;
4
- private storageMode;
5
- private key?;
6
- constructor(configLoader: () => Promise<Config<{
7
- api?: ApiConfigSchema;
8
- }>>, storageMode?: 'json' | 'cookie', key?: string | undefined);
9
- loadAdapter(): Promise<ApiAdapterInterface<BaseApiAdapterConfig, ApiAdapterRequestConfig, string>>;
10
- }
11
- export { LoadDirectusApiProvider };
@@ -1,50 +0,0 @@
1
- import { ApiClientDirectus } from './client.deprecated';
2
- import { ApiStaticDirectus } from './static.deprecated';
3
- import { ApiAuthDirectus } from './auth.deprecated';
4
- import {} from '@tanglemedia/svelte-starter-core';
5
- class LoadDirectusApiProvider {
6
- configLoader;
7
- storageMode;
8
- key;
9
- constructor(configLoader, storageMode = 'json', key) {
10
- this.configLoader = configLoader;
11
- this.storageMode = storageMode;
12
- this.key = key;
13
- }
14
- async loadAdapter() {
15
- const conf = await this.configLoader();
16
- const config = (p) => conf.config(p);
17
- const apiAdapterKey = this.key === 'auth' ? 'auth' : this.key || config('api.default');
18
- const directusType = apiAdapterKey === 'auth'
19
- ? this.key
20
- : config(`api.adapters.${apiAdapterKey}.type`) || 'client';
21
- console.log(`api.apaters.${apiAdapterKey}.type`);
22
- if (!apiAdapterKey) {
23
- throw new Error(`No adapter key specified`);
24
- }
25
- if (directusType) {
26
- if (directusType === 'client') {
27
- const protocol = config(`api.adapters.${apiAdapterKey}.protocol`) || '';
28
- const host = config(`api.adapters.${apiAdapterKey}.host`) || '';
29
- return new ApiClientDirectus(`${protocol}://${host}`.trim(), this.storageMode);
30
- }
31
- else if (directusType === 'auth') {
32
- const protocol = config(`api.adapters.${apiAdapterKey}.protocol`) || '';
33
- const host = config(`api.adapters.${apiAdapterKey}.host`) || '';
34
- return new ApiAuthDirectus(`${protocol}://${host}`.trim(), this.storageMode);
35
- }
36
- else {
37
- const protocol = config(`api.adapters.${apiAdapterKey}.protocol`) || '';
38
- const host = config(`api.adapters.${apiAdapterKey}.host`) || '';
39
- const accessToken = config(`api.adapters.${apiAdapterKey}.access_token`) || '';
40
- return new ApiStaticDirectus(`${protocol}://${host}`.trim(), accessToken);
41
- }
42
- }
43
- else {
44
- const protocol = config(`api.adapters.${apiAdapterKey}.protocol`) || '';
45
- const host = config(`api.adapters.${apiAdapterKey}.host`) || '';
46
- return new ApiClientDirectus(`${protocol}://${host}`.trim(), this.storageMode);
47
- }
48
- }
49
- }
50
- export { LoadDirectusApiProvider };
@@ -1,22 +0,0 @@
1
- import type { BaseApiAdapterConfig } from '@tanglemedia/svelte-starter-core';
2
- type BaseApiMethods = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
3
- declare class ApiStaticDirectus {
4
- private baseURL;
5
- private directusAccessToken;
6
- private directus;
7
- constructor(baseURL: string, directusAccessToken: string);
8
- private init;
9
- getConfig<T extends object>(configuration?: unknown): BaseApiAdapterConfig;
10
- request<T>(method: BaseApiMethods, url: string, query?: Record<string, unknown>): Promise<T>;
11
- createUser(data: {
12
- email: string;
13
- password: string;
14
- first_name: string;
15
- last_name: string;
16
- role: string;
17
- } | object): Promise<{
18
- message: string;
19
- type: string;
20
- }>;
21
- }
22
- export { ApiStaticDirectus };
@@ -1,58 +0,0 @@
1
- import { createDirectus, createUser, rest, staticToken } from '@directus/sdk';
2
- class ApiStaticDirectus {
3
- baseURL;
4
- directusAccessToken;
5
- directus;
6
- constructor(baseURL, directusAccessToken) {
7
- this.baseURL = baseURL;
8
- this.directusAccessToken = directusAccessToken;
9
- this.init();
10
- }
11
- init() {
12
- try {
13
- this.directus = createDirectus(this.baseURL)
14
- .with(rest())
15
- .with(staticToken(this.directusAccessToken));
16
- }
17
- catch (error) {
18
- console.error(`Error initializing Directus admin:`, error);
19
- throw error;
20
- }
21
- }
22
- getConfig(configuration) {
23
- // return this.directus as DirectusClient<T> & RestClient<object>;
24
- const client = this.directus;
25
- // Add the 'configuration' property to the returned object
26
- const config = {
27
- configuration: configuration ?? {} // Use the provided configuration or an empty object if not provided
28
- };
29
- return Object.assign(client, config);
30
- }
31
- async request(method, url, query) {
32
- try {
33
- const response = await this.directus.request(() => {
34
- const params = JSON.stringify(query);
35
- return {
36
- path: `${url}?${params}`,
37
- method: method
38
- };
39
- });
40
- return response;
41
- }
42
- catch (error) {
43
- console.error(`Error request:`, error);
44
- throw error;
45
- }
46
- }
47
- async createUser(data) {
48
- try {
49
- await this.directus.request(createUser(data));
50
- return { message: 'You have successfully registered your account', type: 'success' };
51
- }
52
- catch (error) {
53
- console.error(`Error creating a user:`, error);
54
- throw error;
55
- }
56
- }
57
- }
58
- export { ApiStaticDirectus };
@@ -1,110 +0,0 @@
1
- import type { AuthenticationClient, AuthenticationConfig } from '@directus/sdk';
2
- import { authentication, createDirectus, readMe, refresh, rest, updateMe } from '@directus/sdk';
3
- import type { DirectusClient, RestClient } from '@directus/sdk';
4
- import { AuthLocalStorage } from './storage/local-storage';
5
-
6
- const authenticationConfig: AuthenticationConfig = {
7
- storage: new AuthLocalStorage(),
8
- autoRefresh: true,
9
- msRefreshBeforeExpires: 30000,
10
- credentials: 'include'
11
- };
12
-
13
- class ApiAuthDirectus {
14
- private baseURL: string;
15
- private storageMode: 'json' | 'cookie';
16
- private directus: DirectusClient<object> & RestClient<object> & AuthenticationClient<object>;
17
-
18
- constructor(baseURL: string, storageMode: 'json' | 'cookie' = 'json') {
19
- this.baseURL = baseURL;
20
- this.storageMode = storageMode;
21
- this.init();
22
- }
23
-
24
- private init<T extends object>(): void {
25
- try {
26
- if (this.storageMode === 'json') {
27
- this.directus = createDirectus<T>(this.baseURL)
28
- .with(rest({ credentials: 'include' }))
29
- .with(authentication('json', authenticationConfig));
30
- } else {
31
- this.directus = createDirectus<T>(this.baseURL)
32
- .with(authentication('cookie', { credentials: 'include' }))
33
- .with(rest({ credentials: 'include' }));
34
- }
35
- } catch (error) {
36
- console.error(`Error initializing Directus:`, error);
37
- throw error;
38
- }
39
- }
40
-
41
- public getConfig<T extends object>(): DirectusClient<T> & RestClient<object> {
42
- return this.directus as DirectusClient<T> & RestClient<object>;
43
- }
44
-
45
- public async refresh<T>(): Promise<T> {
46
- try {
47
- const response = await this.directus.request<T>(refresh());
48
- return response;
49
- } catch (error) {
50
- console.error(`Error refreshing :`, error);
51
- throw error;
52
- }
53
- }
54
-
55
- public async getToken<T>(): Promise<T> {
56
- try {
57
- const response = await this.directus.getToken();
58
- return response;
59
- } catch (error) {
60
- console.error(`Error refreshing :`, error);
61
- throw error;
62
- }
63
- }
64
-
65
- public async login<T>(email: string, password: string): Promise<T> {
66
- try {
67
- const response = await this.directus.login(email, password);
68
- return response;
69
- } catch (error) {
70
- console.error(`Error login :`, error);
71
- throw error;
72
- }
73
- }
74
-
75
- public async logout<T>(): Promise<T> {
76
- try {
77
- const response = await this.directus.logout();
78
- return response;
79
- } catch (error) {
80
- console.error(`Error refreshing :`, error);
81
- throw error;
82
- }
83
- }
84
-
85
- public async getCurrentUser<T>(fields: string[] | null = null): Promise<T> {
86
- try {
87
- if (!this.getToken()) await this.refresh();
88
- const response = await this.directus.request<T>(
89
- readMe({ fields: fields ? fields : ['*', 'roles.*'] })
90
- );
91
- return response;
92
- } catch (error) {
93
- console.error(`Error refreshing :`, error);
94
- throw error;
95
- }
96
- }
97
-
98
- public async updateCurrentUser<T>(data: object): Promise<T> {
99
- try {
100
- if (!this.getToken()) await this.refresh();
101
- const response = await this.directus.request<T>(updateMe(data));
102
- return response;
103
- } catch (error) {
104
- console.error(`Error refreshing :`, error);
105
- throw error;
106
- }
107
- }
108
- }
109
-
110
- export { ApiAuthDirectus };
@@ -1,206 +0,0 @@
1
- import type { AuthenticationConfig, DirectusClient, RestClient } from '@directus/sdk';
2
- import {
3
- aggregate,
4
- authentication,
5
- createDirectus,
6
- createItem,
7
- deleteItem,
8
- readItem,
9
- readItems,
10
- rest,
11
- updateItem,
12
- uploadFiles
13
- } from '@directus/sdk';
14
- import type {
15
- AnyObject,
16
- ApiAdapterInterface,
17
- ApiAdapterRequestConfig,
18
- BaseApiAdapterConfig
19
- } from '@tanglemedia/svelte-starter-core';
20
- import { AuthLocalStorage } from './storage/local-storage';
21
-
22
- const authenticationConfig: AuthenticationConfig = {
23
- storage: new AuthLocalStorage(),
24
- autoRefresh: true,
25
- msRefreshBeforeExpires: 30000,
26
- credentials: 'include'
27
- };
28
-
29
- type BaseApiMethods = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
30
-
31
- type ApiId = string | number;
32
-
33
- class ApiClientDirectus implements ApiAdapterInterface {
34
- private baseURL: string;
35
- private storageMode: 'json' | 'cookie';
36
- private directus: DirectusClient<object> & RestClient<object>;
37
-
38
- constructor(baseURL: string, storageMode: 'json' | 'cookie' = 'json') {
39
- this.baseURL = baseURL;
40
- this.storageMode = storageMode;
41
- this.init();
42
- }
43
-
44
- private init<T extends object>(): void {
45
- try {
46
- if (this.storageMode === 'json') {
47
- this.directus = createDirectus<T>(this.baseURL)
48
- .with(rest({ credentials: 'include' }))
49
- .with(authentication('json', authenticationConfig));
50
- } else {
51
- this.directus = createDirectus<T>(this.baseURL)
52
- .with(authentication('cookie', { credentials: 'include' }))
53
- .with(rest({ credentials: 'include' }));
54
- }
55
- } catch (error) {
56
- console.error(`Error initializing Directus:`, error);
57
- throw error;
58
- }
59
- }
60
-
61
- public getConfig<T extends object>(configuration?: unknown): BaseApiAdapterConfig {
62
- // return this.directus as DirectusClient<T> & RestClient<object>;
63
- const client = this.directus as DirectusClient<T> & RestClient<object>;
64
-
65
- // Add the 'configuration' property to the returned object
66
- const config: BaseApiAdapterConfig = {
67
- configuration: configuration ?? {} // Use the provided configuration or an empty object if not provided
68
- };
69
-
70
- return Object.assign(client, config);
71
- }
72
-
73
- public async request<T>(
74
- method: BaseApiMethods,
75
- url: string,
76
- query?: Record<string, unknown>
77
- ): Promise<T> {
78
- try {
79
- const response = await this.directus.request<T>(() => {
80
- const params = JSON.stringify(query);
81
- return {
82
- path: `${url}?${params}`,
83
- method: method
84
- };
85
- });
86
- return response;
87
- } catch (error) {
88
- console.error(`Error request:`, error);
89
- throw error;
90
- }
91
- }
92
-
93
- public async find<T>(collection: string, query?: Record<string, unknown>): Promise<T> {
94
- // console.log('in find');
95
- try {
96
- // console.log(`Find ${collection}`)
97
- const response = await this.directus.request<T>(readItems(collection, query));
98
- return response;
99
- } catch (error) {
100
- console.error(`Error fetching all ${collection}:`, error);
101
- throw error;
102
- }
103
- }
104
-
105
- public async findOne<T>(
106
- collection: string,
107
- key?: ApiId,
108
- query?: Record<string, unknown>
109
- ): Promise<T> {
110
- try {
111
- const response = await this.directus.request<T>(readItem(collection, key, query));
112
- return response;
113
- } catch (error) {
114
- console.error(`Error fetching ${collection}:`, error);
115
- throw error;
116
- }
117
- }
118
-
119
- public async aggregate<T>(collection: string, query?: Record<string, unknown>): Promise<T> {
120
- try {
121
- const response = await this.directus.request<T>(
122
- aggregate(collection, {
123
- aggregate: {
124
- count: 'id'
125
- },
126
- query
127
- })
128
- );
129
- return response;
130
- } catch (error) {
131
- console.error(`Error fetching total of ${collection}:`, error);
132
- throw error;
133
- }
134
- }
135
-
136
- public async patch<T>(
137
- collection: string,
138
- key: ApiId,
139
- query?: Record<string, unknown>
140
- ): Promise<T> {
141
- try {
142
- const response = await this.directus.request<T>(updateItem(collection, key, query));
143
- return response;
144
- } catch (error) {
145
- console.error(`Error updating all ${collection}:`, error);
146
- throw error;
147
- }
148
- }
149
-
150
- public async post<T>(
151
- collection: string,
152
- data: AnyObject,
153
- query?: Record<string, unknown>
154
- ): Promise<T> {
155
- try {
156
- const response = await this.directus.request<T>(createItem(collection, data, query));
157
- return response;
158
- } catch (error) {
159
- console.error(`Error creating items ${collection}:`, error);
160
- throw error;
161
- }
162
- }
163
-
164
- public async delete<T>(collection: string, key?: ApiId): Promise<T> {
165
- try {
166
- const response = await this.directus.request<T>(deleteItem(collection, key));
167
- return response;
168
- } catch (error) {
169
- console.error(`Error deleting items ${collection}:`, error);
170
- throw error;
171
- }
172
- }
173
-
174
- public async put<T>(
175
- collection: string,
176
- payload: AnyObject,
177
- config?: ApiAdapterRequestConfig,
178
- key?: ApiId
179
- ): Promise<T> {
180
- try {
181
- if (key) {
182
- const response = await this.directus.request<T>(updateItem(collection, key, payload));
183
- return response;
184
- } else {
185
- console.error(`Error updating all ${collection}: no key specified`);
186
- throw new Error('No key specified');
187
- }
188
- } catch (error) {
189
- console.error(`Error updating all ${collection}:`, error);
190
- throw error;
191
- }
192
- }
193
-
194
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
195
- public async upload<T>(path: string = '', data: FormData): Promise<T> {
196
- try {
197
- const response = await this.directus.request<T>(uploadFiles(data));
198
- return response;
199
- } catch (error) {
200
- console.error(`Error uploading file:`, error);
201
- throw error;
202
- }
203
- }
204
- }
205
-
206
- export { ApiClientDirectus };
@@ -1,60 +0,0 @@
1
- import { ApiClientDirectus } from './client.deprecated';
2
- import { ApiStaticDirectus } from './static.deprecated';
3
- import { ApiAuthDirectus } from './auth.deprecated';
4
- import {
5
- type ApiAdapterProviderInterface,
6
- type ApiAdapterInterface,
7
- type ApiAdapterRequestConfig,
8
- type BaseApiAdapterConfig,
9
- type Config,
10
- type ApiConfigSchema
11
- } from '@tanglemedia/svelte-starter-core';
12
-
13
- class LoadDirectusApiProvider implements ApiAdapterProviderInterface {
14
- constructor(
15
- private readonly configLoader: () => Promise<Config<{ api?: ApiConfigSchema }>>,
16
- private storageMode: 'json' | 'cookie' = 'json',
17
- private key?: string | undefined
18
- ) {}
19
-
20
- async loadAdapter(): Promise<
21
- ApiAdapterInterface<BaseApiAdapterConfig, ApiAdapterRequestConfig, string>
22
- > {
23
- const conf = await this.configLoader();
24
- const config = (p: string) => conf.config(p);
25
-
26
- const apiAdapterKey =
27
- this.key === 'auth' ? 'auth' : this.key || (config('api.default') as string);
28
- const directusType =
29
- apiAdapterKey === 'auth'
30
- ? this.key
31
- : (config(`api.adapters.${apiAdapterKey}.type`) as string) || 'client';
32
- console.log(`api.apaters.${apiAdapterKey}.type`);
33
-
34
- if (!apiAdapterKey) {
35
- throw new Error(`No adapter key specified`);
36
- }
37
- if (directusType) {
38
- if (directusType === 'client') {
39
- const protocol: string = config(`api.adapters.${apiAdapterKey}.protocol`) || '';
40
- const host: string = config(`api.adapters.${apiAdapterKey}.host`) || '';
41
- return new ApiClientDirectus(`${protocol}://${host}`.trim(), this.storageMode);
42
- } else if (directusType === 'auth') {
43
- const protocol: string = config(`api.adapters.${apiAdapterKey}.protocol`) || '';
44
- const host: string = config(`api.adapters.${apiAdapterKey}.host`) || '';
45
- return new ApiAuthDirectus(`${protocol}://${host}`.trim(), this.storageMode);
46
- } else {
47
- const protocol: string = config(`api.adapters.${apiAdapterKey}.protocol`) || '';
48
- const host: string = config(`api.adapters.${apiAdapterKey}.host`) || '';
49
- const accessToken: string = config(`api.adapters.${apiAdapterKey}.access_token`) || '';
50
- return new ApiStaticDirectus(`${protocol}://${host}`.trim(), accessToken);
51
- }
52
- } else {
53
- const protocol: string = config(`api.adapters.${apiAdapterKey}.protocol`) || '';
54
- const host: string = config(`api.adapters.${apiAdapterKey}.host`) || '';
55
- return new ApiClientDirectus(`${protocol}://${host}`.trim(), this.storageMode);
56
- }
57
- }
58
- }
59
-
60
- export { LoadDirectusApiProvider };
@@ -1,77 +0,0 @@
1
- import { createDirectus, createUser, rest, staticToken } from '@directus/sdk';
2
- import type { DirectusClient, RestClient, StaticTokenClient } from '@directus/sdk';
3
- import type { AnyObject, BaseApiAdapterConfig } from '@tanglemedia/svelte-starter-core';
4
-
5
- type BaseApiMethods = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
6
-
7
- class ApiStaticDirectus {
8
- private baseURL: string;
9
- private directusAccessToken: string;
10
- private directus: DirectusClient<AnyObject> & RestClient<object> & StaticTokenClient<object>;
11
-
12
- constructor(baseURL: string, directusAccessToken: string) {
13
- this.baseURL = baseURL;
14
- this.directusAccessToken = directusAccessToken;
15
- this.init();
16
- }
17
-
18
- private init<T extends object>(): void {
19
- try {
20
- this.directus = createDirectus<T>(this.baseURL)
21
- .with(rest())
22
- .with(staticToken(this.directusAccessToken));
23
- } catch (error) {
24
- console.error(`Error initializing Directus admin:`, error);
25
- throw error;
26
- }
27
- }
28
-
29
- public getConfig<T extends object>(configuration?: unknown): BaseApiAdapterConfig {
30
- // return this.directus as DirectusClient<T> & RestClient<object>;
31
- const client = this.directus as DirectusClient<T> & RestClient<object>;
32
-
33
- // Add the 'configuration' property to the returned object
34
- const config: BaseApiAdapterConfig = {
35
- configuration: configuration ?? {} // Use the provided configuration or an empty object if not provided
36
- };
37
-
38
- return Object.assign(client, config);
39
- }
40
-
41
- public async request<T>(
42
- method: BaseApiMethods,
43
- url: string,
44
- query?: Record<string, unknown>
45
- ): Promise<T> {
46
- try {
47
- const response = await this.directus.request<T>(() => {
48
- const params = JSON.stringify(query);
49
- return {
50
- path: `${url}?${params}`,
51
- method: method
52
- };
53
- });
54
- return response;
55
- } catch (error) {
56
- console.error(`Error request:`, error);
57
- throw error;
58
- }
59
- }
60
-
61
- public async createUser(
62
- data:
63
- | { email: string; password: string; first_name: string; last_name: string; role: string }
64
- | object
65
- ): Promise<{ message: string; type: string }> {
66
- try {
67
- await this.directus.request(createUser(data));
68
-
69
- return { message: 'You have successfully registered your account', type: 'success' };
70
- } catch (error) {
71
- console.error(`Error creating a user:`, error);
72
- throw error;
73
- }
74
- }
75
- }
76
-
77
- export { ApiStaticDirectus };