Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@janiscommerce/api-get

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@janiscommerce/api-get - npm Package Compare versions

Comparing version 4.1.0 to 4.2.0

lib/data-helpers/fields.js

8

CHANGELOG.md

@@ -10,2 +10,10 @@ # Changelog

## [4.2.0] - 2023-01-23
### Added
_ New _parameter_ `fields` to select specific fields to be responded.
_ New _parameter_ `excludeFields` to select specific fields to be excluded in the response.
- Now the _getter_ `fieldsToSelect` can be `false` to prevent to use `fields` _parameter_.
- New _getter_ `fieldsToExclude` to define witch fields must be excluded from the response.
- New _getter_ `fixedFields` to define witch fields must be responded and can't be excluded.
## [4.1.0] - 2022-05-31

@@ -12,0 +20,0 @@ ### Added

15

lib/api-get-error.js

@@ -10,4 +10,10 @@ 'use strict';

class ApiGetError extends Error {
/**
* @class ApiGetError
* @extends Error
* @classdesc It is used for error handling of the ApiGet class
*/
module.exports = class ApiGetError extends Error {
/**

@@ -24,7 +30,6 @@ * Get the error codes

};
}
/**
* @param {Error} err The details of the error
* @param {Object|string} err The details of the error
* @param {Number} code The error code

@@ -44,4 +49,2 @@ */

}
}
module.exports = ApiGetError;
};

65

lib/api-get.js
'use strict';
const { API } = require('@janiscommerce/api');
const { struct } = require('@janiscommerce/superstruct');
const path = require('path');
const ApiGetError = require('./api-get-error');
const EndpointParser = require('./helpers/endpoint-parser');
const Fields = require('./data-helpers/fields');
/**
* @class ApiGet
* @extends API
* @classdesc Use this to get individual documents from the database by Api.
*/
/**
* @typedef {Object} ApiGetError A instance of APIGetError class

@@ -16,2 +27,29 @@ */

/**
* Get the fields to select from the DB.
*
* @returns {Array|false|undefined} - The fields to select
*/
get fieldsToSelect() {
return undefined;
}
/**
* Get the fields to be excluded from the response
*
* @returns {Array|undefined} - The fields to be excluded
*/
get fieldsToExclude() {
return undefined;
}
/**
* Get the fixed fields, this are fields that can't be removed from responses
*
* @returns {Array|undefined} - The fixed fields
*/
get fixedFields() {
return undefined;
}
/**
* Perform validations before processing

@@ -30,2 +68,4 @@ * Set the Model to use and parse the Endpoint

this._validateFields();
return this.postValidate();

@@ -37,2 +77,3 @@ }

* Validation will only be performed if database driver has `idStruct` getter implemented.
* @throws {Error} When id does not pass the validation
* @returns {void}

@@ -56,2 +97,22 @@ */

/**
* It is to perform validations for the fields and excludeFields parameters
* @throws {ApiGetError} if the received fields or excludedFields are invalid
* @returns {void}
*/
_validateFields() {
this.fields = new Fields(this.fieldsToSelect, this.fieldsToExclude, this.fixedFields);
try {
const structFields = struct.optional(this.fields.struct());
structFields(this.data);
} catch(e) {
throw new ApiGetError(e, ApiGetError.codes.INVALID_REQUEST_DATA);
}
}
/**
* It is to perform extra validations

@@ -77,2 +138,3 @@ * @returns {*}

const getParams = {
...this.fields.getParams(this.data),
filters: this._parseFilters(filters),

@@ -83,5 +145,2 @@ page: 1,

if(this.fieldsToSelect)
getParams.fields = this.fieldsToSelect;
const record = await this.model.get(getParams);

@@ -88,0 +147,0 @@

{
"name": "@janiscommerce/api-get",
"version": "4.1.0",
"version": "4.2.0",
"description": "A package to handle Janis Get APIs",

@@ -23,2 +23,3 @@ "main": "lib/index.js",

"devDependencies": {
"@janiscommerce/model": "^6.8.2",
"eslint": "^8.4.1",

@@ -28,8 +29,7 @@ "eslint-config-airbnb-base": "^13.2.0",

"husky": "^7.0.4",
"mocha": "^9.1.3",
"mocha": "^9.2.2",
"mock-require": "^3.0.3",
"nyc": "^15.1.0",
"sinon": "^12.0.1",
"typescript": "^4.5.2",
"@janiscommerce/superstruct": "^1.2.0"
"typescript": "^4.5.2"
},

@@ -45,4 +45,5 @@ "files": [

"dependencies": {
"@janiscommerce/api": "^6.4.2"
"@janiscommerce/api": "^6.6.1",
"@janiscommerce/superstruct": "^1.2.1"
}
}

@@ -20,12 +20,18 @@ # API Get

class MyApiGet extends ApiGet {
const FORBIDDEN_NAME = 'Voldemort';
module.exports = class MyApiGet extends ApiGet {
get fieldsToSelect() {
return [
'id',
'name',
'status'
];
return ['name', 'status'];
}
get fieldsToExclude() {
return ['error'];
}
get fixedFields() {
return ['code'];
}
async format(record) {

@@ -65,5 +71,3 @@ return {

}
}
module.exports = MyApiGet;
};
```

@@ -79,2 +83,103 @@

## ApiGet
The following getters and methods can be used to customize and validate your List API.
All of them are optional.
### get modelName()
Returns model name. It is intent to be used to change the model's name and it will not get the model name from endpoint
### get fieldsToSelect()
_Since_ `1.2.0`
This is used to determinate which fields should be selected from the DB.
**Important**: The `id` field is always returned.
If set as `false`. The _parameter_ `fields` will be ignored.
If a field is not found in the document it will be ignored.
### get fieldsToExclude()
_Since_ `4.2.0`
This is used to determinate witch fields must be excluded from the response.
If set as `false`. The _parameter_ `excludeFields` will be ignored.
**Important**: The `id` field is always returned.
If a field is not found in the document it will be ignored.
### get fixedFields()
_Since_ `4.2.0`
This is used to determinate witch fields **should always be returned**.
If a field is not found in the document it will be ignored.
## Reducing responses
_Since_ `4.2.0`
An Api defined with **ApiGet** can be reduced using new parameters `fields` and `excludeFields`.
This parameters will be passed to the **model** for reducing the response on the database-side.
For the following examples we will be using an invented product with the information
```json
{
"id": 1,
"code": "t-shirt",
"name": "Shirt white and blue",
"price": 200.5,
"status": "active"
}
```
<details>
<summary>Example: Reducing response with fields</summary>
When using `fields` we are telling the database the specific fields we wanna receive in the response.
**Important**. When using `fields`, `excludeFields` will be ignored.
```bash
curl --location -g --request GET 'https://my-catalog.com/api/product/1?fields[0]=code&fields[1]=name'
// expected output: { id: 1, code: 't-shirt', name: 'Shirt white and blue' }
```
</details>
<details>
<summary>Example: Reducing response with excludeFields</summary>
When using `excludeFields` we are telling the database the specific fields we **don't** wanna receive in the response.
**Important**. When using `fields`, `excludeFields` will be ignored.
```bash
curl --location -g --request GET 'https://my-catalog.com/api/product/1?excludeFields[0]=price'
// expected output: { id: 1, code: 't-shirt', name: 'Shirt white and blue', status: 'active' }
```
</details>
### async format(record)
You can use this to format your record before this is returned.
For example, mapping DB friendly values to user friendly values, add default values, translation keys, etc.
### async postValidate()
You can use this to perform extra validations before getting the record.
If it returns a Promise, it will be awaited.
## ✔️ Path ID validation

@@ -92,3 +197,3 @@ The `ID` in the `pathParameters` can be validated if the database needs it in order to avoid problems. If this feature is active, the statusCode for this kind of error will be `400`. This validation has a default behavior (Model version 6.3.0 or higher is needed), and can also be customized for specific needs.

**eg: Adding validation for parent `ids`**
```javascript
```js
validateId() {

@@ -108,3 +213,3 @@

**eg:**
```javascript
```js
validateId() {

@@ -111,0 +216,0 @@ // Do nothing

export = ApiGetError;
/**
* @typedef CodesError
* @property {Number} INVALID_REQUEST_DATA
* @property {Number} INVALID_ENTITY
* @property {Number} INTERNAL_ERROR
*/
declare class ApiGetError extends Error {

@@ -15,7 +9,7 @@ /**

/**
* @param {Error} err The details of the error
* @param {Object|string} err The details of the error
* @param {Number} code The error code
*/
constructor(err: Error, code: number);
message: string | Error;
constructor(err: any | string, code: number);
message: any;
code: number;

@@ -22,0 +16,0 @@ previousError: Error;

export = ApiGet;
declare class ApiGet extends API {
/**
* Get the fields to select from the DB.
*
* @returns {Array|false|undefined} - The fields to select
*/
get fieldsToSelect(): false | any[];
/**
* Get the fields to be excluded from the response
*
* @returns {Array|undefined} - The fields to be excluded
*/
get fieldsToExclude(): any[];
/**
* Get the fixed fields, this are fields that can't be removed from responses
*
* @returns {Array|undefined} - The fixed fields
*/
get fixedFields(): any[];
/**
* Perform validations before processing

@@ -13,2 +31,3 @@ * Set the Model to use and parse the Endpoint

* Validation will only be performed if database driver has `idStruct` getter implemented.
* @throws {Error} When id does not pass the validation
* @returns {void}

@@ -18,2 +37,9 @@ */

/**
* It is to perform validations for the fields and excludeFields parameters
* @throws {ApiGetError} if the received fields or excludedFields are invalid
* @returns {void}
*/
_validateFields(): void;
fields: Fields;
/**
* It is to perform extra validations

@@ -73,2 +99,3 @@ * @returns {*}

import { API } from "@janiscommerce/api";
import Fields = require("./data-helpers/fields");
/**

@@ -75,0 +102,0 @@ * A instance of APIGetError class

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc