kodzero-front-sdk-alfa 0.0.2
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/.eslintrc.cjs +13 -0
- package/.eslintrc.json +16 -0
- package/README.md +313 -0
- package/dist/Kodzero.d.ts +33 -0
- package/dist/Kodzero.js +22 -0
- package/dist/auth/base.d.ts +15 -0
- package/dist/auth/base.js +18 -0
- package/dist/auth/email.d.ts +23 -0
- package/dist/auth/email.js +70 -0
- package/dist/auth/index.d.ts +13 -0
- package/dist/auth/index.js +21 -0
- package/dist/auth/tokens.d.ts +10 -0
- package/dist/auth/tokens.js +22 -0
- package/dist/errors/KodzeroApiError.d.ts +7 -0
- package/dist/errors/KodzeroApiError.js +10 -0
- package/dist/errors/KodzeroValidationError.d.ts +5 -0
- package/dist/errors/KodzeroValidationError.js +8 -0
- package/dist/fetcher/InterceptorManager.d.ts +9 -0
- package/dist/fetcher/InterceptorManager.js +42 -0
- package/dist/fetcher/MiddlewareManager.d.ts +9 -0
- package/dist/fetcher/MiddlewareManager.js +42 -0
- package/dist/fetcher/index.d.ts +77 -0
- package/dist/fetcher/index.js +194 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +49 -0
- package/dist/model/BaseModel.d.ts +38 -0
- package/dist/model/BaseModel.js +119 -0
- package/dist/model/baseModelOptionsSchema.d.ts +2 -0
- package/dist/model/baseModelOptionsSchema.js +10 -0
- package/dist/model/configSchema.d.ts +0 -0
- package/dist/model/configSchema.js +1 -0
- package/dist/model/constants.d.ts +8 -0
- package/dist/model/constants.js +7 -0
- package/dist/model/createModel.d.ts +28 -0
- package/dist/model/createModel.js +159 -0
- package/dist/model/errors/KodzeroApiError.d.ts +7 -0
- package/dist/model/errors/KodzeroApiError.js +10 -0
- package/dist/model/index.d.ts +4 -0
- package/dist/model/index.js +4 -0
- package/dist/model/modelFactory.d.ts +50 -0
- package/dist/model/modelFactory.js +41 -0
- package/dist/model/modelSchema.d.ts +0 -0
- package/dist/model/modelSchema.js +1 -0
- package/dist/model/schemas/baseModel.d.ts +6 -0
- package/dist/model/schemas/baseModel.js +25 -0
- package/dist/model/schemas/baseModelOptionsSchema.d.ts +2 -0
- package/dist/model/schemas/baseModelOptionsSchema.js +10 -0
- package/dist/model/statics/getAll.d.ts +2 -0
- package/dist/model/statics/getAll.js +4 -0
- package/dist/model/utils/processUrl.d.ts +2 -0
- package/dist/model/utils/processUrl.js +7 -0
- package/dist/model/utils/validateApiResponse.d.ts +2 -0
- package/dist/model/utils/validateApiResponse.js +14 -0
- package/dist/schemas/baseAuth.d.ts +6 -0
- package/dist/schemas/baseAuth.js +18 -0
- package/dist/schemas/baseModel copy.d.ts +6 -0
- package/dist/schemas/baseModel copy.js +25 -0
- package/dist/schemas/baseModel.d.ts +6 -0
- package/dist/schemas/baseModel.js +25 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/dist/types/responses.d.ts +14 -0
- package/dist/types/responses.js +1 -0
- package/dist/utils/buildURL.d.ts +2 -0
- package/dist/utils/buildURL.js +7 -0
- package/dist/utils/buildURL_rename.d.ts +2 -0
- package/dist/utils/buildURL_rename.js +7 -0
- package/dist/utils/processUrl.d.ts +2 -0
- package/dist/utils/processUrl.js +7 -0
- package/dist/utils/validateApiResponse.d.ts +2 -0
- package/dist/utils/validateApiResponse.js +14 -0
- package/jest.config.ts +190 -0
- package/nodemon.json +4 -0
- package/package.json +29 -0
- package/src/Kodzero.ts +35 -0
- package/src/auth/base.ts +37 -0
- package/src/auth/email.ts +123 -0
- package/src/auth/index.ts +43 -0
- package/src/auth/tokens.ts +49 -0
- package/src/errors/KodzeroApiError.ts +17 -0
- package/src/errors/KodzeroValidationError.ts +12 -0
- package/src/model/BaseModel.ts +210 -0
- package/src/model/constants.ts +7 -0
- package/src/model/createModel.ts +237 -0
- package/src/model/index.ts +12 -0
- package/src/schemas/baseAuth.ts +28 -0
- package/src/schemas/baseModel.ts +35 -0
- package/src/tsconfig.json +103 -0
- package/src/types/module.d.ts +2 -0
- package/src/types/responses.ts +14 -0
- package/src/utils/buildURL_rename.ts +8 -0
- package/src/utils/validateApiResponse.ts +17 -0
package/.eslintrc.cjs
ADDED
package/.eslintrc.json
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
# Kodzero Frontend SDK [alfa]
|
|
2
|
+
|
|
3
|
+
A lightweight OOP library for frontend applications to easily interact with Kodzero backend APIs. This SDK provides a clean, object-oriented approach for working with your backend data models and authentication.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install kodzero-front-sdk-alfa
|
|
9
|
+
```
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Authentication
|
|
13
|
+
|
|
14
|
+
The SDK provides built-in authentication features:
|
|
15
|
+
|
|
16
|
+
```javascript
|
|
17
|
+
// Initialize the SDK with your backend URL
|
|
18
|
+
const kodzero = new Kodzero({
|
|
19
|
+
host: 'https://api.your-backend.com'
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
// Sign up a new user
|
|
23
|
+
const signupResult = await kodzero.auth.signup({
|
|
24
|
+
email: 'user@example.com',
|
|
25
|
+
password: 'secure_password'
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
// Sign in
|
|
29
|
+
const signinResult = await kodzero.auth.signin({
|
|
30
|
+
email: 'user@example.com',
|
|
31
|
+
password: 'secure_password'
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
// Verify current authentication status
|
|
35
|
+
const verified = await kodzero.auth.verify();
|
|
36
|
+
|
|
37
|
+
// Refresh the token
|
|
38
|
+
const refreshed = await kodzero.auth.refresh();
|
|
39
|
+
|
|
40
|
+
// Sign out
|
|
41
|
+
await kodzero.auth.signout();
|
|
42
|
+
|
|
43
|
+
// Manually set tokens (useful for persisting sessions)
|
|
44
|
+
kodzero.auth.setTokens('access_token', 'refresh_token');
|
|
45
|
+
|
|
46
|
+
// Clear tokens
|
|
47
|
+
kodzero.auth.clearTokens();
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Model
|
|
51
|
+
|
|
52
|
+
Creating and using models is the core functionality of the SDK. Models provide an OOP approach to interacting with your backend data.
|
|
53
|
+
|
|
54
|
+
### Creating a Model
|
|
55
|
+
|
|
56
|
+
```javascript
|
|
57
|
+
import Schema from 'validno';
|
|
58
|
+
|
|
59
|
+
// Define your data model interface
|
|
60
|
+
interface User {
|
|
61
|
+
_id?: string;
|
|
62
|
+
name: string;
|
|
63
|
+
email: string;
|
|
64
|
+
createdAt?: Date;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Optional: Create a schema for validation
|
|
68
|
+
const userSchema = new Schema({
|
|
69
|
+
_id: { type: String },
|
|
70
|
+
name: { type: String },
|
|
71
|
+
email: { type: String },
|
|
72
|
+
createdAt: { type: Date }
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// Create a model for the 'users' collection
|
|
76
|
+
const User = kodzero.createModel<User>({
|
|
77
|
+
collection: 'users',
|
|
78
|
+
schema: userSchema // Optional but recommended for validation
|
|
79
|
+
});
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### Instance Methods
|
|
83
|
+
|
|
84
|
+
After creating a model, you can use its instance methods to work with individual records:
|
|
85
|
+
|
|
86
|
+
```javascript
|
|
87
|
+
// Create a new user instance
|
|
88
|
+
const newUser = new User({
|
|
89
|
+
name: 'John Doe',
|
|
90
|
+
email: 'john@example.com'
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// Save the new user to the database (creates a new record)
|
|
94
|
+
await newUser.save();
|
|
95
|
+
console.log('New user ID:', newUser.data()._id);
|
|
96
|
+
|
|
97
|
+
// Get the current data
|
|
98
|
+
const userData = newUser.data();
|
|
99
|
+
|
|
100
|
+
// Update user data with the set method
|
|
101
|
+
newUser.set('name', 'Jane Doe');
|
|
102
|
+
// Or with object syntax for multiple fields
|
|
103
|
+
newUser.set({
|
|
104
|
+
name: 'Jane Doe',
|
|
105
|
+
email: 'jane@example.com'
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
// Update the record in the database
|
|
109
|
+
await newUser.update();
|
|
110
|
+
|
|
111
|
+
// Or use save() which handles both create and update
|
|
112
|
+
await newUser.save();
|
|
113
|
+
|
|
114
|
+
// Validate the data against the schema
|
|
115
|
+
const validationResult = newUser.validate();
|
|
116
|
+
if (!validationResult.ok) {
|
|
117
|
+
console.error('Validation errors:', validationResult.joinErrors());
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Delete the user from the database
|
|
121
|
+
await newUser.delete();
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Advanced Model Usage
|
|
125
|
+
|
|
126
|
+
### Custom Methods
|
|
127
|
+
|
|
128
|
+
You can extend your models with custom methods:
|
|
129
|
+
|
|
130
|
+
```javascript
|
|
131
|
+
// Define your model interface
|
|
132
|
+
interface Car {
|
|
133
|
+
_id?: string;
|
|
134
|
+
make: string;
|
|
135
|
+
model: string;
|
|
136
|
+
year: number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Define custom methods interface
|
|
140
|
+
interface CarMethods {
|
|
141
|
+
getDescription: () => string;
|
|
142
|
+
isVintage: () => boolean;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Create the model with the custom methods type
|
|
146
|
+
const Car = kodzero.createModel<Car, CarMethods>({
|
|
147
|
+
collection: 'cars',
|
|
148
|
+
schema: carSchema
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
// Register custom methods
|
|
152
|
+
Car.registerMethod('getDescription', function() {
|
|
153
|
+
const data = this.data();
|
|
154
|
+
return `${data.make} ${data.model} (${data.year})`;
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
Car.registerMethod('isVintage', function() {
|
|
158
|
+
return this.data().year < 1980;
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// Usage
|
|
162
|
+
const myCar = await Car.get('car_id_here');
|
|
163
|
+
console.log(myCar.getDescription()); // "Toyota Corolla (2020)"
|
|
164
|
+
console.log(myCar.isVintage()); // false
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Static Model Operations
|
|
168
|
+
|
|
169
|
+
Models provide static methods for working with collections as a whole:
|
|
170
|
+
|
|
171
|
+
### Fetching Data
|
|
172
|
+
|
|
173
|
+
```javascript
|
|
174
|
+
// Find a document and return plain data (not an instance)
|
|
175
|
+
const userData = await User.find('user_id_here');
|
|
176
|
+
|
|
177
|
+
// Find multiple documents with optional query parameters
|
|
178
|
+
const users = await User.findMany({
|
|
179
|
+
page: 1, // Pagination: page number
|
|
180
|
+
perPage: 10, // Items per page
|
|
181
|
+
search: 'John', // Search term
|
|
182
|
+
sort: '-createdAt', // Sort by field (prefix with - for descending)
|
|
183
|
+
fields: ['name', 'email'] // Specific fields to return
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
// Create a single document
|
|
187
|
+
const newUser = await User.create({
|
|
188
|
+
name: 'Alice',
|
|
189
|
+
email: 'alice@example.com'
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
// Update a single document by ID
|
|
193
|
+
const updatedUser = await User.update('user_id', {
|
|
194
|
+
name: 'Updated Name'
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
// Delete a document by ID
|
|
198
|
+
const deleted = await User.delete('user_id');
|
|
199
|
+
|
|
200
|
+
// Get distinct values
|
|
201
|
+
const distinctNames = await User.distinct(['name']);
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### Batch Operations
|
|
205
|
+
|
|
206
|
+
The SDK supports batch operations for improved efficiency:
|
|
207
|
+
|
|
208
|
+
```javascript
|
|
209
|
+
// Create multiple records at once
|
|
210
|
+
const newUsers = await User.createMany([
|
|
211
|
+
{ name: 'John', email: 'john@example.com' },
|
|
212
|
+
{ name: 'Jane', email: 'jane@example.com' }
|
|
213
|
+
]);
|
|
214
|
+
|
|
215
|
+
// Update multiple records
|
|
216
|
+
const updates = await User.updateMany([
|
|
217
|
+
{ _id: 'id1', name: 'Updated Name 1' },
|
|
218
|
+
{ _id: 'id2', email: 'updated2@example.com' }
|
|
219
|
+
]);
|
|
220
|
+
|
|
221
|
+
// Delete multiple records
|
|
222
|
+
const deleteResults = await User.deleteMany(['id1', 'id2', 'id3']);
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
## Validation
|
|
226
|
+
|
|
227
|
+
The SDK uses the `validno` library for schema-based validation. When creating a model with a schema, you can validate your data:
|
|
228
|
+
|
|
229
|
+
```javascript
|
|
230
|
+
// Define a schema with validation rules
|
|
231
|
+
const carSchema = new Schema({
|
|
232
|
+
_id: { type: String },
|
|
233
|
+
make: { type: String, required: true },
|
|
234
|
+
model: { type: String, required: true },
|
|
235
|
+
year: { type: Number, min: 1900, max: 2100 }
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
const Car = kodzero.createModel<Car>({
|
|
239
|
+
collection: 'cars',
|
|
240
|
+
schema: carSchema
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
const car = new Car({
|
|
244
|
+
make: 'Toyota',
|
|
245
|
+
// Missing required 'model' field will be caught
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
const validationResult = car.validate();
|
|
249
|
+
if (!validationResult.ok) {
|
|
250
|
+
console.error('Validation failed:', validationResult.joinErrors());
|
|
251
|
+
// Output: "Validation failed: model is required"
|
|
252
|
+
}
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
## Working with Nested Data
|
|
256
|
+
|
|
257
|
+
You can easily work with nested data structures:
|
|
258
|
+
|
|
259
|
+
```javascript
|
|
260
|
+
// Create a model with nested data
|
|
261
|
+
interface Profile {
|
|
262
|
+
_id?: string;
|
|
263
|
+
user: {
|
|
264
|
+
name: string;
|
|
265
|
+
contact: {
|
|
266
|
+
email: string;
|
|
267
|
+
phone?: string;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const Profile = kodzero.createModel<Profile>({
|
|
273
|
+
collection: 'profiles'
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
const profile = new Profile({
|
|
277
|
+
user: {
|
|
278
|
+
name: 'John Doe',
|
|
279
|
+
contact: {
|
|
280
|
+
email: 'john@example.com'
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
// Set nested properties
|
|
286
|
+
profile.set('user.contact.phone', '123-456-7890');
|
|
287
|
+
|
|
288
|
+
// Or with object syntax for multiple nested properties
|
|
289
|
+
profile.set({
|
|
290
|
+
'user.name': 'Jane Doe',
|
|
291
|
+
'user.contact.email': 'jane@example.com'
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
await profile.save();
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
## Error Handling
|
|
298
|
+
|
|
299
|
+
The SDK provides proper error handling for API requests:
|
|
300
|
+
|
|
301
|
+
```javascript
|
|
302
|
+
try {
|
|
303
|
+
const user = await User.get('non_existent_id');
|
|
304
|
+
} catch (error) {
|
|
305
|
+
if (error.name === 'KodzeroApiError') {
|
|
306
|
+
console.error('API Error:', error.message, error.status);
|
|
307
|
+
} else if (error.name === 'KodzeroValidationError') {
|
|
308
|
+
console.error('Validation Error:', error.message);
|
|
309
|
+
} else {
|
|
310
|
+
console.error('Unexpected error:', error);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
```
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import FluidFetch from "fluid-fetch";
|
|
2
|
+
import { KodzeroAuth } from "./auth/index.js";
|
|
3
|
+
import { ModelOptions } from "./model/BaseModel.js";
|
|
4
|
+
import { TokensManagerClass } from "./auth/tokens.js";
|
|
5
|
+
interface Options {
|
|
6
|
+
host: string;
|
|
7
|
+
}
|
|
8
|
+
declare class Kodzero {
|
|
9
|
+
host: string;
|
|
10
|
+
auth: KodzeroAuth;
|
|
11
|
+
tokensManager: TokensManagerClass;
|
|
12
|
+
api: typeof FluidFetch;
|
|
13
|
+
constructor(options: Options);
|
|
14
|
+
createModel: <T extends {
|
|
15
|
+
_id?: string;
|
|
16
|
+
}, M = {}>(options: Omit<ModelOptions, "host">) => {
|
|
17
|
+
new (data: T): import("./model/BaseModel.js").default<T> & M;
|
|
18
|
+
get(id: string): Promise<import("./model/BaseModel.js").default<T> & M>;
|
|
19
|
+
registerMethod<K extends keyof M>(name: K, fn: M[K]): void;
|
|
20
|
+
find(id: string): Promise<T>;
|
|
21
|
+
findMany(options?: import("./model/createModel.js").FindManyOptions | {}): Promise<T[]>;
|
|
22
|
+
create(data: T): Promise<T>;
|
|
23
|
+
createMany(data: T[]): Promise<T[]>;
|
|
24
|
+
update(id: string, data: Partial<T>): Promise<T>;
|
|
25
|
+
updateMany(updates: Partial<T>[]): Promise<T[]>;
|
|
26
|
+
delete(id: string): Promise<boolean>;
|
|
27
|
+
deleteMany(ids: string[]): Promise<Record<string, boolean>>;
|
|
28
|
+
distinct(fields: string[], filter?: Record<string, any>): Promise<string[]>;
|
|
29
|
+
host: string;
|
|
30
|
+
collection: string;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export default Kodzero;
|
package/dist/Kodzero.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import FluidFetch from "fluid-fetch";
|
|
2
|
+
import { KodzeroAuth } from "./auth/index.js";
|
|
3
|
+
import createModel from "./model/createModel.js";
|
|
4
|
+
import { TokensManagerClass } from "./auth/tokens.js";
|
|
5
|
+
class Kodzero {
|
|
6
|
+
constructor(options) {
|
|
7
|
+
this.createModel = (options) => {
|
|
8
|
+
return createModel(Object.assign(Object.assign({}, options), { host: this.host }), this.api);
|
|
9
|
+
};
|
|
10
|
+
this.tokensManager = new TokensManagerClass('', '');
|
|
11
|
+
this.host = options.host;
|
|
12
|
+
this.api = new FluidFetch();
|
|
13
|
+
this.auth = new KodzeroAuth({ host: options.host }, this.api, this.tokensManager);
|
|
14
|
+
this.api.middlewares.request.use((req) => {
|
|
15
|
+
const accessToken = this.tokensManager.access;
|
|
16
|
+
if (accessToken)
|
|
17
|
+
req.headers['Authorization'] = accessToken;
|
|
18
|
+
return req;
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export default Kodzero;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import FluidFetch from "fluid-fetch";
|
|
2
|
+
import { AuthOptions } from "./index.js";
|
|
3
|
+
import { TokensManagerClass } from "./tokens.js";
|
|
4
|
+
export declare class KodzeroAuthBase {
|
|
5
|
+
host: string;
|
|
6
|
+
api: typeof FluidFetch;
|
|
7
|
+
tokensManager: TokensManagerClass;
|
|
8
|
+
constructor(options: AuthOptions, api: typeof FluidFetch, tokensManager: TokensManagerClass);
|
|
9
|
+
_handleApiError(response: Response): Promise<void>;
|
|
10
|
+
signin: (...args: any[]) => Promise<any> | void;
|
|
11
|
+
signup: (...args: any[]) => Promise<any> | void;
|
|
12
|
+
refresh: (...args: any[]) => Promise<any> | void;
|
|
13
|
+
signout: (...args: any[]) => Promise<any> | void;
|
|
14
|
+
verify: (...args: any[]) => Promise<any> | void;
|
|
15
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import BaseAuthSchema from "../schemas/baseAuth.js";
|
|
2
|
+
import validateApiResponse from "../utils/validateApiResponse.js";
|
|
3
|
+
export class KodzeroAuthBase {
|
|
4
|
+
constructor(options, api, tokensManager) {
|
|
5
|
+
this.signin = (...args) => { };
|
|
6
|
+
this.signup = (...args) => { };
|
|
7
|
+
this.refresh = (...args) => { };
|
|
8
|
+
this.signout = (...args) => { };
|
|
9
|
+
this.verify = (...args) => { };
|
|
10
|
+
BaseAuthSchema.validateOrThrow(options);
|
|
11
|
+
this.host = options.host;
|
|
12
|
+
this.api = api;
|
|
13
|
+
this.tokensManager = tokensManager;
|
|
14
|
+
}
|
|
15
|
+
_handleApiError(response) {
|
|
16
|
+
return validateApiResponse(response);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import FluidFetch from "fluid-fetch";
|
|
2
|
+
import { AuthOptions } from "./index.js";
|
|
3
|
+
import { KodzeroAuthBase } from "./base.js";
|
|
4
|
+
import { TokensManagerClass } from "./tokens.js";
|
|
5
|
+
interface KodzeroAuthEmailSignin {
|
|
6
|
+
email: string;
|
|
7
|
+
password: string;
|
|
8
|
+
}
|
|
9
|
+
declare class KodzeroAuthEmail extends KodzeroAuthBase {
|
|
10
|
+
tokensManager: TokensManagerClass;
|
|
11
|
+
collection: "auth/password";
|
|
12
|
+
constructor(options: AuthOptions, api: typeof FluidFetch, tokensManager: TokensManagerClass);
|
|
13
|
+
_setTokens: (access: string, refresh?: string) => void;
|
|
14
|
+
signin: (input: KodzeroAuthEmailSignin) => Promise<{
|
|
15
|
+
access: string;
|
|
16
|
+
refresh: string;
|
|
17
|
+
}>;
|
|
18
|
+
signup: (userData: Record<string, string>) => Promise<Record<string, any>>;
|
|
19
|
+
verify: () => Promise<any>;
|
|
20
|
+
refresh: () => Promise<any>;
|
|
21
|
+
signout: () => Promise<any>;
|
|
22
|
+
}
|
|
23
|
+
export default KodzeroAuthEmail;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { KodzeroAuthBase } from "./base.js";
|
|
2
|
+
import buildURL from "../utils/buildURL_rename.js";
|
|
3
|
+
class KodzeroAuthEmail extends KodzeroAuthBase {
|
|
4
|
+
constructor(options, api, tokensManager) {
|
|
5
|
+
super(options, api, tokensManager);
|
|
6
|
+
this._setTokens = (access, refresh) => {
|
|
7
|
+
this.tokensManager.setAccess(access);
|
|
8
|
+
if (refresh)
|
|
9
|
+
this.tokensManager.setRefresh(refresh);
|
|
10
|
+
};
|
|
11
|
+
this.signin = async (input) => {
|
|
12
|
+
const url = buildURL(this.host, this.collection + '/signin');
|
|
13
|
+
const response = await this.api.post(url, input)
|
|
14
|
+
.headers({ 'Content-Type': 'application/json' });
|
|
15
|
+
await this._handleApiError(response);
|
|
16
|
+
const json = await response.json();
|
|
17
|
+
if (json.ok && json.tokens && json.tokens.access && json.tokens.refresh) {
|
|
18
|
+
this._setTokens(json.tokens.access, json.tokens.refresh);
|
|
19
|
+
}
|
|
20
|
+
return json.tokens;
|
|
21
|
+
};
|
|
22
|
+
this.signup = async (userData) => {
|
|
23
|
+
const url = buildURL(this.host, this.collection + '/signup');
|
|
24
|
+
const response = await this.api.post(url, userData)
|
|
25
|
+
.headers({ 'Content-Type': 'application/json' });
|
|
26
|
+
await this._handleApiError(response);
|
|
27
|
+
const json = await response.json();
|
|
28
|
+
if (json.ok && json.result && json.result.tokens.access && json.result.tokens.refresh) {
|
|
29
|
+
this._setTokens(json.result.tokens.access, json.result.tokens.refresh);
|
|
30
|
+
}
|
|
31
|
+
return json.result.user;
|
|
32
|
+
};
|
|
33
|
+
this.verify = async () => {
|
|
34
|
+
try {
|
|
35
|
+
const url = buildURL(this.host, this.collection + '/verify');
|
|
36
|
+
const response = await this.api.get(url);
|
|
37
|
+
const json = await response.json();
|
|
38
|
+
return json.ok ? true : false;
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
console.warn("Token verification error:", error);
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
this.refresh = async () => {
|
|
46
|
+
const url = buildURL(this.host, this.collection + '/refresh');
|
|
47
|
+
const response = await this.api.post(url, { refresh: this.tokensManager.refresh })
|
|
48
|
+
.headers({ 'Content-Type': 'application/json' });
|
|
49
|
+
await this._handleApiError(response);
|
|
50
|
+
const json = await response.json();
|
|
51
|
+
if (json.ok && json.tokens && json.tokens.access) {
|
|
52
|
+
this.tokensManager.setAccess(json.tokens.access);
|
|
53
|
+
}
|
|
54
|
+
return json.ok ? true : false;
|
|
55
|
+
};
|
|
56
|
+
this.signout = async () => {
|
|
57
|
+
const url = buildURL(this.host, this.collection + '/signout');
|
|
58
|
+
const response = await this.api.post(url, {})
|
|
59
|
+
.headers({ 'Content-Type': 'application/json' });
|
|
60
|
+
await this._handleApiError(response);
|
|
61
|
+
const json = await response.json();
|
|
62
|
+
if (json.ok)
|
|
63
|
+
this.tokensManager.clear();
|
|
64
|
+
return json.ok ? true : false;
|
|
65
|
+
};
|
|
66
|
+
this.tokensManager = tokensManager;
|
|
67
|
+
this.collection = "auth/password";
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
export default KodzeroAuthEmail;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import FluidFetch from "fluid-fetch";
|
|
2
|
+
import { KodzeroAuthBase } from "./base.js";
|
|
3
|
+
import KodzeroAuthEmail from "./email.js";
|
|
4
|
+
import { TokensManagerClass } from "./tokens.js";
|
|
5
|
+
export interface AuthOptions {
|
|
6
|
+
host: string;
|
|
7
|
+
}
|
|
8
|
+
export declare class KodzeroAuth extends KodzeroAuthBase {
|
|
9
|
+
email: KodzeroAuthEmail;
|
|
10
|
+
setTokens: (access: string, refresh?: string) => void;
|
|
11
|
+
clearTokens: () => void;
|
|
12
|
+
constructor(options: AuthOptions, api: typeof FluidFetch, tokensManager: TokensManagerClass);
|
|
13
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { KodzeroAuthBase } from "./base.js";
|
|
2
|
+
import KodzeroAuthEmail from "./email.js";
|
|
3
|
+
export class KodzeroAuth extends KodzeroAuthBase {
|
|
4
|
+
constructor(options, api, tokensManager) {
|
|
5
|
+
super(options, api, tokensManager);
|
|
6
|
+
this.email = new KodzeroAuthEmail(options, api, tokensManager);
|
|
7
|
+
this.signin = this.email.signin;
|
|
8
|
+
this.signup = this.email.signup;
|
|
9
|
+
this.signout = this.email.signout;
|
|
10
|
+
this.verify = this.email.verify;
|
|
11
|
+
this.refresh = this.email.refresh;
|
|
12
|
+
this.setTokens = (access, refresh) => {
|
|
13
|
+
tokensManager.setAccess(access);
|
|
14
|
+
if (refresh)
|
|
15
|
+
tokensManager.setRefresh(refresh);
|
|
16
|
+
};
|
|
17
|
+
this.clearTokens = () => {
|
|
18
|
+
tokensManager.clear();
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare class TokensManagerClass {
|
|
2
|
+
access: string;
|
|
3
|
+
refresh: string;
|
|
4
|
+
constructor(access?: string, refresh?: string);
|
|
5
|
+
hasAccess(): boolean | "";
|
|
6
|
+
hasRefresh(): boolean | "";
|
|
7
|
+
setAccess(token: string): void;
|
|
8
|
+
setRefresh(token: string): void;
|
|
9
|
+
clear(): void;
|
|
10
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export class TokensManagerClass {
|
|
2
|
+
constructor(access = '', refresh = '') {
|
|
3
|
+
this.access = access;
|
|
4
|
+
this.refresh = refresh;
|
|
5
|
+
}
|
|
6
|
+
hasAccess() {
|
|
7
|
+
return this.access && this.access !== '';
|
|
8
|
+
}
|
|
9
|
+
hasRefresh() {
|
|
10
|
+
return this.refresh && this.refresh !== '';
|
|
11
|
+
}
|
|
12
|
+
setAccess(token) {
|
|
13
|
+
this.access = token;
|
|
14
|
+
}
|
|
15
|
+
setRefresh(token) {
|
|
16
|
+
this.refresh = token;
|
|
17
|
+
}
|
|
18
|
+
clear() {
|
|
19
|
+
this.access = '';
|
|
20
|
+
this.refresh = '';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
class KodzeroApiError extends Error {
|
|
2
|
+
constructor(url, statusCode, message, details) {
|
|
3
|
+
super(message);
|
|
4
|
+
this.name = "KodzeroApiError";
|
|
5
|
+
this.url = url;
|
|
6
|
+
this.statusCode = statusCode;
|
|
7
|
+
this.details = details || '';
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export default KodzeroApiError;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
declare class MiddlewareManager<T> {
|
|
2
|
+
private handlers;
|
|
3
|
+
private idCounter;
|
|
4
|
+
use(fulfilled: (value: T) => Promise<T> | T, rejected?: (error: any) => any): number;
|
|
5
|
+
eject(id: number): void;
|
|
6
|
+
clear(): void;
|
|
7
|
+
runMiddlewares(value: T): Promise<T>;
|
|
8
|
+
}
|
|
9
|
+
export default MiddlewareManager;
|