Get all employees plugin + filter by last_name

 avatar
unknown
javascript
3 years ago
2.1 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": {}
       }
       ]
   }
 *
 *
 */

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('location_ids', null, 'neq');

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

        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...