Test plugin + custom condition types

 avatar
unknown
javascript
4 years ago
2.6 kB
8
Indexable
const SearchCriteria = require('magento-searchcriteria-builder');

/**
 *
 * API url:
   /V1/store-locator/employees
 *
 *
 searchCriteria[filterGroups][0][filters][0][field] = location_ids
 searchCriteria[filterGroups][0][filters][0][value] = null
 searchCriteria[filterGroups][0][filters][0][conditionType] = neq
 *
 *
 * API response interface:
 * {
       "items": [
       {
         "entity_id": 0,
         "created_at": "string",
         "first_name": "string",
         "last_name": "string",
         "position_id": "string",
         "email": "string",
         "phone": "string",
         "brand_ids": "string",
         "location_ids": "string",
         "image": "string",
         "sort_order": 0,
         "extension_attributes": {}
       }
       ]
   }

 * Magento condition types 
 *
 "eq" => equalValue
 "neq" => notEqualValue
 "like" => likeValue
 "nlike" => notLikeValue
 "is" => isValue
 "in" => inValues
 "nin" => notInValues
 "notnull" => valueIsNotNull
 "null" => valueIsNull
 "moreq" => moreOrEqualValue
 "gt" => greaterValue
 "lt" => lessValue
 "gteq" => greaterOrEqualValue
 "lteq" => lessOrEqualValue
 "finset" => valueInSet
 "from" => fromValue, "to" => toValue
 *
 *
 */

module.exports = ({ config, db, router, cache, apiStatus, apiError, getRestApiClient }) => {
  const url = '/store-locator/employees';
  const createRestClient = () => {
    const client = getRestApiClient();
    client.addMethods('storeLocator', (restClient) => {
      const module = {};
      module.getAllEmployees = (lastName) => {
        const searchCriteria = new SearchCriteria();
        searchCriteria.applyFilter('created_at', '2021-06-16', 'from');
        searchCriteria.applyFilter('created_at', '2021-06-18', 'to');

        // if (lastName) searchCriteria.applyFilter('last_name', lastName, 'eq');
        searchCriteria.applySort('last_name', 'ASC');

        searchCriteria.setPageSize(4);

        const stringifiedQuery = searchCriteria.build();
        console.log('Stringified query: ', stringifiedQuery);

        return restClient.get(url + '?' + stringifiedQuery);
      };

      return module;
    });

    return client;
  };

  router.get('', async (req, res) => {
    const { last_name } = req.query;
    const client = createRestClient();
    client.storeLocator.getAllEmployees(last_name)
      .then(response => {
        apiStatus(res, response, 200);
      })
      .catch(err => {
        console.error('Magento error: ', err);
        apiError(res, err);
      });
  });

  return {
    domainName: '@grupakmk',
    pluginName: 'test-plugin',
    route: '/test',
    router
  };
};
Editor is loading...