@mnfst/sdk
Version:
Manifest JavaScript SDK
347 lines (346 loc) • 11.8 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { BaseSDK } from '../../core/common/src/index.js';
export default class Manifest extends BaseSDK {
/**
* Create a new instance of the client.
*
* @param baseUrl The Manifest backend URL address (Without ending slash). Default: http://localhost:1111
*/
constructor(baseUrl) {
super();
/**
* The Manifest backend base URL (Without ending slash).
*/
this.baseUrl = 'http://localhost:1111/api';
/**
* The headers of the request.
*/
this.headers = {
'Content-Type': 'application/json'
};
if (baseUrl) {
this.baseUrl = baseUrl + '/api';
}
}
/**
* Set the slug of the single entity to query.
*
* @param slug The slug of the single entity to query.
*
* @returns an object containing the methods to get and update the single entity.
*
* @example client.single('about').get()
* @example client.single('home').update({ title: 'New title' })
*/
single(slug) {
this.slug = slug;
this.isSingleEntity = true;
this.queryParams = {};
return {
/**
* Fetches a single entity by slug.
*
* @returns A Promise resolving to the single entity.
*/
get: () => __awaiter(this, void 0, void 0, function* () {
return this.fetch({
path: `/singles/${this.slug}`
});
}),
/**
* Updates a single entity by slug doing a full replacement (PUT).
*
* @param data The data to update the single entity with.
* @returns A Promise resolving to the updated single entity.
*/
update: (data) => __awaiter(this, void 0, void 0, function* () {
return this.fetch({
path: `/singles/${this.slug}`,
method: 'PUT',
body: data
});
}),
/**
* Updates a single entity by slug doing a partial replacement (PATCH).
*
* @param data The data to update the single entity with.
* @returns A Promise resolving to the updated single entity.
*/
patch: (data) => __awaiter(this, void 0, void 0, function* () {
return this.fetch({
path: `/singles/${this.slug}`,
method: 'PATCH',
body: data
});
})
};
}
/**
* Get the paginated list of items of the entity.
*
* @param paginationParams - Optional pagination parameters.
*
* @returns A Promise that resolves a Paginator object containing entities of type T, based on the input.
*/
find(paginationParams) {
return __awaiter(this, void 0, void 0, function* () {
return this.fetch({
path: `/collections/${this.slug}`,
queryParams: Object.assign(Object.assign({}, this.queryParams), paginationParams)
});
});
}
/**
* Get an item of the entity.
*
* @param id The id of the item to get.
*
* @returns The item of the entity.
* @example client.from('cats').findOne(1);
*
**/
findOneById(id) {
return __awaiter(this, void 0, void 0, function* () {
return this.fetch({
path: `/collections/${this.slug}/${id}`,
queryParams: Object.assign({}, this.queryParams)
});
});
}
/**
* Create an item of the entity.
*
* @param itemDto The DTO of the item to create.
*
* @returns The created item.
*/
create(itemDto) {
return __awaiter(this, void 0, void 0, function* () {
return this.fetch({
path: `/collections/${this.slug}`,
method: 'POST',
body: itemDto
});
});
}
/**
* Update an item of the entity doing a full replace. Leaving blank fields and relations will remove them. Use patch for partial updates.
*
* @param id The id of the item to update.
* @param itemDto The DTO of the item to update.
*
* @returns The updated item.
* @example client.from('cats').update(1, { name: 'updated name' });
*/
update(id, itemDto) {
return __awaiter(this, void 0, void 0, function* () {
return this.fetch({
path: `/collections/${this.slug}/${id}`,
method: 'PUT',
body: itemDto
});
});
}
/**
* Partially update an item of the entity. Leaving blank fields and relations will not remove them. Use update for full replaces.
*
* @param id The id of the item to update.
* @param itemDto The DTO of the item to update.
*
* @returns The updated item.
* @example client.from('cats').update(1, { name: 'updated name' });
*/
patch(id, itemDto) {
return __awaiter(this, void 0, void 0, function* () {
return this.fetch({
path: `/collections/${this.slug}/${id}`,
method: 'PATCH',
body: itemDto
});
});
}
/**
*
* Delete an item of the entity.
*
* @param id The id of the item to delete.
*
* @returns The id of the deleted item.
* @example client.from('cats').delete(1);
*/
delete(id) {
return __awaiter(this, void 0, void 0, function* () {
return this.fetch({
path: `/collections/${this.slug}/${id}`,
method: 'DELETE'
}).then(() => id);
});
}
/**
*
* Login as any authenticable entity.
*
* @param entitySlug The slug of the entity to login as.
* @param email The email of the entity to login as.
* @param password The password of the entity to login as.
*
* @returns an object with the token if logged in, false otherwise.
*/
login(entitySlug, email, password) {
return __awaiter(this, void 0, void 0, function* () {
const response = (yield this.fetch({
path: `/auth/${entitySlug}/login`,
method: 'POST',
body: {
email,
password
}
}));
if (!response.token) {
throw new Error('Login failed: No token received');
}
this.headers['Authorization'] = `Bearer ${response.token}`;
return { token: response.token };
});
}
/**
*
* Logout as any authenticable entity.
*
* @returns void
*/
logout() {
delete this.headers['Authorization'];
}
/**
* Signup as any authenticable entity but Admin and login.
*
* @param entitySlug The slug of the entity to signup as.
* @param email The email of the entity to signup as.
* @param password The password of the entity to signup as.
*
* @returns true if the signup was successful.
*/
signup(entitySlug, email, password) {
return __awaiter(this, void 0, void 0, function* () {
const response = (yield this.fetch({
path: `/auth/${entitySlug}/signup`,
method: 'POST',
body: {
email,
password
}
}));
this.headers['Authorization'] = `Bearer ${response.token}`;
return true;
});
}
/**
* Gets the current logged in user (me). Use "from('your-entity')" before calling this method.
*
* @returns The current logged in user.
* @example client.from('users').me();
*
*/
me() {
return __awaiter(this, void 0, void 0, function* () {
return this.fetch({
path: `/auth/${this.slug}/me`
});
});
}
fetch(_a) {
return __awaiter(this, arguments, void 0, function* ({ path, method, body, queryParams }) {
const url = new URL(this.baseUrl + path);
Object.entries(queryParams || []).forEach(([key, value]) => {
if (value !== null && value !== undefined) {
url.searchParams.append(key, value.toString());
}
});
return fetch(url.toString(), {
headers: this.headers,
method: method || 'GET',
body: body ? JSON.stringify(body) : undefined
})
.then((res) => res.json())
.catch((err) => {
console.error(err);
return {};
});
});
}
/**
* Upload a file to the entity.
*
* @param property The property of the entity to upload the file to.
* @param file The file to upload.
*
* @returns the path of the uploaded file.
*/
upload(property, file) {
return __awaiter(this, void 0, void 0, function* () {
const formData = new FormData();
formData.append('file', file);
formData.append('entity', this.slug);
formData.append('property', property);
return fetch(`${this.baseUrl}/upload/file`, {
method: 'POST',
body: formData,
headers: {
Authorization: this.headers['Authorization']
}
})
.then((res) => res.json())
.catch((err) => {
console.error(err);
return {};
});
});
}
/**
* Upload an image to the entity.
*
* @param property The property of the entity to upload the image to.
* @param image The image to upload.
*
* @returns an object containing the path of the uploaded image in different sizes.
* */
uploadImage(property, image) {
return __awaiter(this, void 0, void 0, function* () {
const formData = new FormData();
formData.append('image', image);
formData.append('entity', this.slug);
formData.append('property', property);
return fetch(`${this.baseUrl}/upload/image`, {
method: 'POST',
body: formData,
headers: {
Authorization: this.headers['Authorization']
}
})
.then((res) => res.json())
.catch((err) => {
console.error(err);
return {};
});
});
}
/**
* Helper that returns the absolute URL of the image.
*
* @param image The image object containing the different sizes of the image.
*
* @returns The absolute URL of the image.
*/
imageUrl(image, size) {
return `${this.baseUrl.replace(/\/api$/, '')}/storage/${image[size]}`;
}
}