@youcan/js
v1.0.3
Published
YouCan store-front js SDK is a lightweight library that allows you to interact with various aspect of your store thanks to some helper functions.
Downloads
79
Readme
Table of content
Installation
$ npm i @youcan/youcanjs
Or you can use the cdn version Make sure to include the last thing in header tag
<script src="https://unpkg.com/@youcan/js@latest/dist/index.umd.js"></script>
Usage
import YouCanJs from '@youcan/js';
const youcan = YouCanJs.init();
const categories = await youcanjs.category.fetchAll();
Examples
Menus
/**
* Fetch all menus
* @returns {Promise<Menu[]>}
* @throws {ApplicationException} If any error occurs
*/
const menus = await youcanjs.menu.fetch();
Store
/**
* Submit a contact form, after this method execution, the contact form will be sent to the store/email owner
* @param {ContactForm} ContactParams
* @param {string} [ContactParams.name] | required
* @param {string} [ContactParams.email] | required
* @param {string} [ContactParams.subject] | required
* @returns {Promise<void>}
* @throws {ApplicationException} If any error occurs
*/
await youcanjs.store.contact({
email: '[email protected]', // required
subject: 'Test', // required
message: 'Put your message here', // required
});
Pages
/**
* Fetch all pages
* @returns {Promise<Page[]>}
* @throws {ApplicationException} If any error occurs
*/
const pages = await youcanjs.page.fetchAll().data();
Upload
/**
* Upload a file
* @param {File} file
* @returns {Promise<UploadResponse>}
* @return {string} UploadResponse.link
* @return {string} UploadResponse.name
* @throws {ApplicationException} If any error occurs
*/
const uploadResponse = await youcanjs.product.upload(file);
Products
/**
* Fetch product by id or slug
* @param {string} idOrSlug | required
* @returns {Promise<Product>}
* @throws {ApplicationException} If any error occurs
*/
const product = await youcanjs.product.fetchByIdOrSlug('ps5');
pagination
Products > Pagination and query filters
Note
There's a difference between paginated and non-paginated methods.
The non-paginated methods return a normal data, while the paginated methods return a PaginationResult
class.
Pagination has been implemented in the following methods:
fetchAll
fetchByCategory
fetchReviews
fetchSubCategories
Here is an example of how to use it, we will use the fetchByCategory
method as an example:
/**
* pagination()
* @return {pagination} pagination info
* @return {number} [pagination.totalPages] total pages
* @return {number} [pagination.currentPage] current page
*/
/* Make sure to call data() always before pagination(), or chain pagination() with an instance of data() */
const res = youcanjs.product.fetchByCategory('id or slug').data().pagination();
/* Or */
const res = youcanjs.product.fetchByCategory('id or slug');
const products = await res.data();
const pagination = products.pagination();
/**
* orderBy()
* @param {string} field | required
* @param {string} order, optional
*/
const res = youcanjs.product.fetchByCategory('id or slug').orderBy('price', 'desc');
/**
* search()
* @param {string} query | required
*/
const res = youcanjs.product.fetchByCategory('id or slug').search('ps5');
const products = await res.data();
/* Or */
const res = youcanjs.product.fetchByCategory('id or slug');
const products = await res.search('ps5').data();
/**
* next()
* @returns {Promise<Product[]>} Next page of products
*/
const res = youcanjs.product.fetchByCategory('id or slug');
/* display the data */
let products = await res.data(); // returns the data
/* display pagination info */
const pagination = res.pagination(); // returns the pagination info
/* paginate to next page */
products = await res.next().data();
/* paginate to previous page */
products = await res.prev().data();
/**
* filterBy()
* @param {string} field, you can only filter by the fields that are available, 'inventory' and 'trashed' | required
* @param {string} value | required
* @param {string} operator | required
*/
const res = youcanjs.product.fetchByCategory('id or slug').filterBy('inventory', 5, '=');
const res2 = youcanjs.product.fetchByCategory('id or slug').filterBy('trashed', true, '=');
/* chain the methods */
products = await res
.search('ps5')
.orderBy('price', 'desc')
.filterBy('inventory', 5, '=')
.next()
.data();
/**
* Fetch all products
* @returns {Promise<Product[]>}
* @throws {ApplicationException} If any error occurs
*/
const res = youcanjs.product.fetchAll();
const products = await res.data(); // returns the data
const pagination = res.pagination(); // returns the pagination info
/**
* Fetch products by category
* @param {string} categoryId | required
* @param {queryOptions} [params] | optional
* @returns {Promise<Product[]>}
* @throws {ApplicationException} If any error occurs
*/
const res = youcanjs.product.fetchByCategory('id or slug');
const products = await res.data(); // returns the data
const pagination = res.pagination(); // returns the pagination info
/**
* Fetch product's reviews
* @param {string} productId | required
* @param {queryOptions} [params] | optional
* @returns {Promise<Review[]>}
* @throws {ApplicationException} If any error occurs
*/
const res = youcanjs.product.fetchReviews('id or slug', { page: 2 });
const reviews = await res.data(); // returns the data
const pagination = res.pagination(); // returns the pagination info
/**
* Submit a product review.
*
* This method allows users to submit reviews for products, which could include ratings, comments, and other relevant feedback.
*
* @param {string} productId | required
* @param {Object} reviewParams | optional
* @param {string} reviewParams.content | optional
* @param {string} reviewParams.email | required
* @param {number} reviewParams.ratings | required
* @param {string} reviewParams.first_name | optional
* @param {string} reviewParams.last_name | optional
* @param {string[]} reviewParams.images_urls | optional
* @param {File[]} reviewParams.images | optional
*
* @returns {Promise<Object>} Returns a promise which resolves with the response data from the submission.
*
* @throws {ApplicationException} If the submission is unsuccessful, an application exception is thrown with more information.
*/
await youcanjs.product.submitReview('productId', {
content: 'Fantastic Product!',
email: '[email protected]',
ratings: 5,
first_name: 'Adil',
last_name: 'Dev',
images_urls: ['https://example.com/image.png'],
images: 'File[]',
});
Categories
/**
* Fetch category by id
* @param {string} id | required
* @returns {Promise<Category>}
* @throws {ApplicationException} If any error occurs
*/
const category = await youcanjs.category.fetch('~~id');
/**
* Fetch all categories
* @returns {Promise<Category[]>}
* @throws {ApplicationException} If any error occurs
*/
const categories = await youcanjs.category.fetchAll();
/**
* Fetch sub categories
* @param {string} categorySlugOrId category id or slug | required
* @param {queryOptions} [params] query options | optional
* @returns {Promise<Category[]>}
* @throws {ApplicationException} If any error occurs
*/
const res = youcanjs.category.fetchSubCategories('apple', { page: 5 });
const categories = await res.data(); // returns the data
const pagination = res.pagination(); // returns the pagination info
Cart
/**
* Fetch cart.
* @return {Promise<Cart>}
* @throws {ApplicationException} If any error occurs.
*/
const cart = await youcanjs.cart.fetch();
/**
* Add product to cart.
* @param [addParams]
* @param {string} [addParams.productVariantId] | required
* @param {string} [addParams.attachedImage] Attached image, It is an optional parameter. | optional
* @param {number} [addParams.quantity] | optional
* @return {Promise<Cart>}
* @throws {ApplicationException} If any error occurs
*/
const cart = await youcanjs.cart.addItem({
productVariantId: '999',
attachedImage: null,
quantity: 1,
});
/**
* Update cart item
* @param [updateParams]
* @param {string} [updateParams.cartItemId] | required
* @param {string} [updateParams.productVariantId] | required
* @param {number} [updateParams.quantity] | required
* @return {Promise<Cart>}
* @throws {ApplicationException} If any error occurs
*/
const cart = await youcanjs.cart.updateItem({
cartItemId: '999',
productVariantId: '123',
quantity: 1,
});
/**
* Remove cart item
* @param [removeParams]
* @param {string} [removeParams.cartItemId] Cart item id | required
* @param {string} [removeParams.productVariantId] | required
* @return {Promise<Cart>}
* @throws {ApplicationException} If any error occurs
*/
const cart = await youcanjs.cart.removeItem({
cartItemId: '999',
productVariantId: '123',
});
/**
* Add note to cart
* @param {string} note | required
* @return {Promise<void>}
* @throws {ApplicationException} If any error occurs
*/
await youcanjs.cart.note('note');
Checkout
Coupons
/**
* Apply coupon to checkout items
* @param {string} couponCode | required
* @return {Promise<Cart>}
*/
const cart = await youcanjs.checkout.applyCoupon('coupon code');
/**
* Remove coupons
* @return {Promise<Cart>}
*/
const cart = await youcanjs.checkout.removeCoupon();
Express Checkout
/**
* Create express checkout
* @param {ExpressCheckoutParams} params | required
* @return {Promise<ExpressCheckout>}
* @throws {ApplicationException} If any error occurs
* @onSuccess {(data: unknown) => void} Callback function to be called on success.
* @onValidationErr {(data: unknown) => void} Callback function to be called on validation error.
* @onSkipShippingStep {(data: unknown) => void} Callback function to be called on skip shipping step.
* @onSkipPaymentStep {(data: unknown) => void} Callback function to be called on skip payment step.
*/
const response = await youcanjs.checkout.placeExpressCheckoutOrder({
productVariantId: '87d04a36-983d-48e4-9933-48299ef58091',
quantity: 1,
fields: {
first_name: 'sdfsd'
}
});
response
.onSuccess((data, redirectToThankyouPage) => {
// Do something on success
console.warn('success', data);
// Use this function to redirect to thankyou page
redirectToThankyouPage();
})
.onValidationErr((data) => {
// Do something on validation error
console.warn('validation error', data);
})
.onSkipShippingStep((data, redirectToShippingPage) => {
// Do something on skipping shipping step
console.warn('skipping shipping step', data);
// Use this function to redirect to shipping page
redirectToShippingPage();
})
.onSkipPaymentStep((data, redirectToPaymentPage) => {
// Do something on skipping payment step
console.warn('skipping payment step', data);
// Use this function to redirect to payment page
redirectToPaymentPage();
})
.catch((err) => {
// Do something on Error
console.error(err);
})
.finally(() => {
// Do something on finally
console.warn('finally 🤙🏻');
});