@tanglemedia/svelte-starter-directus-api 0.0.16 → 0.1.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.
Files changed (43) hide show
  1. package/dist/adapter/api-adapter.d.ts +22 -0
  2. package/dist/adapter/api-adapter.js +100 -0
  3. package/dist/{auth.js → auth.deprecated.js} +3 -42
  4. package/dist/{client.js → client.deprecated.js} +3 -36
  5. package/dist/index.d.ts +9 -4
  6. package/dist/index.js +8 -4
  7. package/dist/{load-directus-api-povider.d.ts → load-directus-api-povider.deprecated.d.ts} +3 -2
  8. package/dist/{load-directus-api-povider.js → load-directus-api-povider.deprecated.js} +16 -11
  9. package/dist/provider/api-adapter.provider.d.ts +7 -0
  10. package/dist/provider/api-adapter.provider.js +21 -0
  11. package/dist/provider/directus.factory.d.ts +6 -0
  12. package/dist/provider/directus.factory.js +41 -0
  13. package/dist/services/auth.d.ts +14 -0
  14. package/dist/services/auth.js +85 -0
  15. package/dist/services/register.d.ts +16 -0
  16. package/dist/services/register.js +18 -0
  17. package/dist/static.deprecated.d.ts +22 -0
  18. package/dist/static.deprecated.js +58 -0
  19. package/dist/storage/local-storage.d.ts +9 -0
  20. package/dist/storage/local-storage.js +30 -0
  21. package/dist/types/adapter.types.d.ts +23 -0
  22. package/dist/types/adapter.types.js +1 -0
  23. package/dist/types/index.d.ts +1 -0
  24. package/dist/types/index.js +1 -0
  25. package/package.json +10 -10
  26. package/src/adapter/api-adapter.ts +164 -0
  27. package/src/{auth.ts → auth.deprecated.ts} +10 -65
  28. package/src/{static.ts → client.deprecated.ts} +31 -33
  29. package/src/index.ts +12 -4
  30. package/src/{load-directus-api-povider.ts → load-directus-api-povider.deprecated.ts} +21 -14
  31. package/src/provider/api-adapter.provider.ts +35 -0
  32. package/src/provider/directus.factory.ts +69 -0
  33. package/src/services/auth.ts +92 -0
  34. package/src/services/register.ts +28 -0
  35. package/src/static.deprecated.ts +77 -0
  36. package/src/storage/local-storage.ts +33 -0
  37. package/src/types/adapter.types.ts +30 -0
  38. package/src/types/index.ts +1 -0
  39. package/dist/static.d.ts +0 -31
  40. package/dist/static.js +0 -151
  41. package/src/client.ts +0 -254
  42. /package/dist/{auth.d.ts → auth.deprecated.d.ts} +0 -0
  43. /package/dist/{client.d.ts → client.deprecated.d.ts} +0 -0
@@ -0,0 +1,69 @@
1
+ import {
2
+ authentication,
3
+ createDirectus,
4
+ graphql,
5
+ rest,
6
+ staticToken,
7
+ type AuthenticationConfig,
8
+ type ClientOptions
9
+ } from '@directus/sdk';
10
+ import { AuthLocalStorage } from '../storage/local-storage';
11
+ import type { DirectusConfig } from '../types/adapter.types';
12
+
13
+ const authConfigDefaults = {
14
+ autoRefresh: false,
15
+ msRefreshBeforeExpires: 0,
16
+ credentials: 'include' as const
17
+ };
18
+
19
+ /**
20
+ * Creates a directus client based on the application configuration
21
+ */
22
+ export const createDirectusClientFactory = <T extends object>(
23
+ {
24
+ baseUrl,
25
+ configuration: { protocol = 'https', host, auth, staticToken: token, graphql: gql, rest: rs }
26
+ }: DirectusConfig,
27
+ options?: ClientOptions
28
+ ) => {
29
+ let url = baseUrl;
30
+
31
+ if (host) {
32
+ url = `${protocol}://${host}`;
33
+ }
34
+
35
+ if (!url) {
36
+ throw new Error('Unable to resolve base url for directus client');
37
+ }
38
+
39
+ // if there is going to be authentication and no rest config has been specified.
40
+ // set the correct defaults
41
+ if (!rs && auth) {
42
+ rs = { credentials: 'include' };
43
+ }
44
+
45
+ let client = createDirectus<T>(url, options).with(rest(rs));
46
+
47
+ if (auth) {
48
+ const { config: c, mode } = auth;
49
+ const { storage, ...config } = { ...authConfigDefaults, ...(c || {}) };
50
+
51
+ const authConfig: AuthenticationConfig = config;
52
+
53
+ if (storage === 'localStorage') {
54
+ authConfig.storage = new AuthLocalStorage();
55
+ }
56
+
57
+ client = client.with(authentication(mode, authConfig));
58
+ }
59
+
60
+ if (token) {
61
+ client = client.with(staticToken(token));
62
+ }
63
+
64
+ if (gql) {
65
+ client = client.with(graphql(gql));
66
+ }
67
+
68
+ return client;
69
+ };
@@ -0,0 +1,92 @@
1
+ import type { AuthenticationClient } from '@directus/sdk';
2
+ import { readFiles, readMe, refresh, updateMe } from '@directus/sdk';
3
+ import type { DirectusClient, RestClient } from '@directus/sdk';
4
+ import { ApiResponse, ServiceAdapterAbstract } from '@tanglemedia/svelte-starter-core';
5
+
6
+ class DirectusAuthServices extends ServiceAdapterAbstract {
7
+ public getDirectus() {
8
+ return this.getAdapterClient<
9
+ DirectusClient<object> & RestClient<object> & AuthenticationClient<object>
10
+ >();
11
+ }
12
+
13
+ // public getConfig<T extends object>(): DirectusClient<T> & RestClient<object> {
14
+ // return this.directus as DirectusClient<T> & RestClient<object>;
15
+ // }
16
+
17
+ public async refresh() {
18
+ try {
19
+ const response = await (await this.getDirectus()).refresh();
20
+ return response;
21
+ } catch (error) {
22
+ console.error(`Error on directus sdk refresh() :`, error);
23
+ throw error;
24
+ }
25
+ }
26
+
27
+ public async getToken() {
28
+ try {
29
+ const response = await (await this.getDirectus()).getToken();
30
+ return response;
31
+ } catch (error) {
32
+ console.error(`Error on directus sdk getToken() :`, error);
33
+ throw error;
34
+ }
35
+ }
36
+
37
+ public async login(email: string, password: string) {
38
+ try {
39
+ const response = await (await this.getDirectus()).login(email, password);
40
+ return response;
41
+ } catch (error) {
42
+ console.error(`Error on directus sdk login() :`, error);
43
+ throw error;
44
+ }
45
+ }
46
+
47
+ public async logout() {
48
+ try {
49
+ const response = await (await this.getDirectus()).logout();
50
+ return response;
51
+ } catch (error) {
52
+ console.error(`Error on directus sdk logout() :`, error);
53
+ throw error;
54
+ }
55
+ }
56
+
57
+ public async getCurrentUser<T>(fields: string[] | null = null): Promise<T> {
58
+ try {
59
+ if (!await this.getToken()) await this.refresh();
60
+ const response = await (
61
+ await this.getDirectus()
62
+ ).request<T>(readMe({ fields: fields ? fields : ['*', 'roles.*'] }));
63
+ return response;
64
+ } catch (error) {
65
+ console.error(`Error on directus sdk readMe() :`, error);
66
+ throw error;
67
+ }
68
+ }
69
+
70
+ public async updateCurrentUser<T>(data: object): Promise<T> {
71
+ try {
72
+ if (!await this.getToken()) await this.refresh();
73
+ const response = await (await this.getDirectus()).request<T>(updateMe(data));
74
+ return response;
75
+ } catch (error) {
76
+ console.error(`Error on directus sdk updateMe() :`, error);
77
+ throw error;
78
+ }
79
+ }
80
+
81
+ public async readFile<T>(query?: Record<string, unknown>): Promise<T> {
82
+ try {
83
+ const response = await (await this.getDirectus()).request<T>(readFiles(query));
84
+ return response;
85
+ } catch (error) {
86
+ console.error('Error on directus sdk readFiles():', error);
87
+ throw error;
88
+ }
89
+ }
90
+ }
91
+
92
+ export { DirectusAuthServices };
@@ -0,0 +1,28 @@
1
+ import { createUser } from '@directus/sdk';
2
+ import type { AuthenticationClient, DirectusClient, RestClient } from '@directus/sdk';
3
+ import { ServiceAdapterAbstract } from '@tanglemedia/svelte-starter-core';
4
+
5
+ class DirectusStaticServices extends ServiceAdapterAbstract {
6
+ public getDirectus() {
7
+ return this.getAdapterClient<
8
+ DirectusClient<object> & RestClient<object> & AuthenticationClient<object>
9
+ >();
10
+ }
11
+
12
+ public async createUser(
13
+ data:
14
+ | { email: string; password: string; first_name: string; last_name: string; role: string }
15
+ | object
16
+ ): Promise<{ message: string; type: string }> {
17
+ try {
18
+ await (await this.getDirectus()).request(createUser(data));
19
+
20
+ return { message: 'You have successfully registered your account', type: 'success' };
21
+ } catch (error) {
22
+ console.error(`Error creating a user:`, error);
23
+ throw error;
24
+ }
25
+ }
26
+ }
27
+
28
+ export { DirectusStaticServices };
@@ -0,0 +1,77 @@
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 };
@@ -0,0 +1,33 @@
1
+ import type { AuthenticationStorage, AuthenticationData } from '@directus/sdk';
2
+ import { BROWSER } from 'esm-env';
3
+ import { LocalStoragePolyFill } from '@tanglemedia/svelte-starter-core';
4
+
5
+ const loadStorage = () => {
6
+ return BROWSER && window && window.localStorage
7
+ ? window.localStorage
8
+ : (new LocalStoragePolyFill() as Storage);
9
+ };
10
+
11
+ export class AuthLocalStorage implements AuthenticationStorage {
12
+ #storage = loadStorage();
13
+
14
+ constructor(private readonly storageKey: string = 'access_token_directus') {}
15
+
16
+ get key() {
17
+ return this.storageKey;
18
+ }
19
+
20
+ // get: () => a | Promise<a | null> | null;
21
+ async get(): Promise<AuthenticationData | null> {
22
+ const data = this.#storage.getItem(this.key);
23
+ return data ? (JSON.parse(data) as AuthenticationData) : null;
24
+ }
25
+
26
+ async set(value: AuthenticationData | null) {
27
+ if (value === null) {
28
+ this.#storage.removeItem(this.key);
29
+ } else {
30
+ this.#storage.setItem(this.key, JSON.stringify(value));
31
+ }
32
+ }
33
+ }
@@ -0,0 +1,30 @@
1
+ import type { AuthenticationMode, GraphqlConfig } from '@directus/sdk';
2
+ import type { BaseApiAdapterConfig } from '@tanglemedia/svelte-starter-core';
3
+
4
+ export type DirectusApiAuthOptions = {
5
+ mode: AuthenticationMode;
6
+ config?: Partial<{
7
+ autoRefresh: boolean;
8
+ msRefreshBeforeExpires: number;
9
+ credentials?: RequestCredentials;
10
+ storage?: 'localStorage' | 'memoryStorage';
11
+ }>;
12
+ };
13
+
14
+ export type DirectusApiAdapterOptions = {
15
+ protocol?: 'http' | 'https';
16
+ host?: string | null;
17
+
18
+ auth?: DirectusApiAuthOptions;
19
+ staticToken?: string;
20
+
21
+ graphql?: GraphqlConfig;
22
+
23
+ rest?: {
24
+ credentials?: RequestCredentials;
25
+ };
26
+ };
27
+
28
+ export type DirectusConfig = BaseApiAdapterConfig<DirectusApiAdapterOptions>;
29
+
30
+ export type SchemaShape = Record<string, object>;
@@ -0,0 +1 @@
1
+ export * from './adapter.types';
package/dist/static.d.ts DELETED
@@ -1,31 +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 ApiStaticDirectus implements ApiAdapterInterface {
5
- private baseURL;
6
- private directusAccessToken;
7
- private directus;
8
- constructor(baseURL: string, directusAccessToken: string);
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
- createUser(data: {
13
- email: string;
14
- password: string;
15
- first_name: string;
16
- last_name: string;
17
- role: string;
18
- } | object): Promise<{
19
- message: string;
20
- type: string;
21
- }>;
22
- find<T>(collection: string, query?: Record<string, unknown>): Promise<T>;
23
- findOne<T>(collection: string, key: ApiId, query?: Record<string, unknown>): Promise<T>;
24
- aggregate<T>(collection: string, query?: Record<string, unknown>): Promise<T>;
25
- patch<T>(collection: string, key: ApiId, query?: Record<string, unknown>): Promise<T>;
26
- post<T>(collection: string, data: AnyObject, query?: Record<string, unknown>): Promise<T>;
27
- delete<T>(collection: string, keys: ApiId): Promise<T>;
28
- put<T>(collection: string, payload: AnyObject, config?: ApiAdapterRequestConfig, key?: ApiId): Promise<T>;
29
- upload<T>(path: string | undefined, data: FormData): Promise<T>;
30
- }
31
- export { ApiStaticDirectus };
package/dist/static.js DELETED
@@ -1,151 +0,0 @@
1
- import { aggregate, createDirectus, createItem, createUser, deleteItem, readItem, readItems, rest, staticToken, updateItem, updateItems, uploadFiles } 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
- async find(collection, query) {
58
- try {
59
- const response = await this.directus.request(readItems(collection, query));
60
- return response;
61
- }
62
- catch (error) {
63
- console.error(`Error fetching all ${collection}:`, error);
64
- throw error;
65
- }
66
- }
67
- async findOne(collection, key, query) {
68
- try {
69
- const response = await this.directus.request(readItem(collection, key, query));
70
- return response;
71
- }
72
- catch (error) {
73
- console.error(`Error fetching ${collection}:`, error);
74
- throw error;
75
- }
76
- }
77
- async aggregate(collection, query) {
78
- try {
79
- const response = await this.directus.request(aggregate(collection, {
80
- aggregate: {
81
- count: 'id'
82
- },
83
- query
84
- }));
85
- return response;
86
- }
87
- catch (error) {
88
- console.error(`Error fetching total of ${collection}:`, error);
89
- throw error;
90
- }
91
- }
92
- async patch(collection, key, query) {
93
- try {
94
- const response = await this.directus.request(updateItems(collection, key, query));
95
- return response;
96
- }
97
- catch (error) {
98
- console.error(`Error updating all ${collection}:`, error);
99
- throw error;
100
- }
101
- }
102
- async post(collection, data, query) {
103
- try {
104
- const response = await this.directus.request(createItem(collection, data, query));
105
- return response;
106
- }
107
- catch (error) {
108
- console.error(`Error creating items ${collection}:`, error);
109
- throw error;
110
- }
111
- }
112
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
113
- async delete(collection, keys) {
114
- try {
115
- const response = await this.directus.request(deleteItem(collection, key));
116
- return response;
117
- }
118
- catch (error) {
119
- console.error(`Error deleting items ${collection}:`, error);
120
- throw error;
121
- }
122
- }
123
- async put(collection, payload, config, key) {
124
- try {
125
- if (key) {
126
- const response = await this.directus.request(updateItem(collection, key, payload));
127
- return response;
128
- }
129
- else {
130
- console.error(`Error updating all ${collection}: no key specified`);
131
- throw new Error('No key specified');
132
- }
133
- }
134
- catch (error) {
135
- console.error(`Error updating all ${collection}:`, error);
136
- throw error;
137
- }
138
- }
139
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
140
- async upload(path = '', data) {
141
- try {
142
- const response = await this.directus.request(uploadFiles(data));
143
- return response;
144
- }
145
- catch (error) {
146
- console.error(`Error uploading file:`, error);
147
- throw error;
148
- }
149
- }
150
- }
151
- export { ApiStaticDirectus };