@janiscommerce/sls-api-upload v6.0.0
sls-api-upload
This package contains several modules to handle upload files, list it, or delete it for Janis APIs.
Installation
npm install @janiscommerce/sls-api-upload
Content
In this package, you can found several modules to create APIs to manage files, uploads, delete or get them.
- A Basic Model
- APIs for Save Files * SLS-API-File-Relation
- APIs for List and Get Files SLS-API-List SLS-API-Get
- API for Delete Files * SLS-API-Delete
Every Module can be customize.
Common Validation
Some APIs Modules offers some custom validation for specfics features such as file size, or file type, but everyone has a common validation hook.
postValidateHook()
In order to add some custom validations you can use re-write this method, can be async, if fails the status-code is setted to 400
by default. If it exist, executes after validate()
and before process()
.
class MyApiUpload extends SlsApiUpload {
// ... other code
postValidateHook() {
if(!Controller.isValidData(this.data))
throw new Error('Invalid Data');
}
};
BaseFileModel
This Class extends from @janiscommerce/model
Model Example
'use strict';
const { BaseFileModel } = require('@janiscommerce/sls-api-upload');
class FileModel extends BaseFileModel {
static get table() {
return 'your_table_files';
}
static get fields() {
return {
...super.fields,
productId: true
};
}
}
Getters
The following getters can be used to customize and validate your BaseFileModel.
static get table()
Optional
Default: "files"
This is used to indicate the name of the files table/collection
static get table() {
return 'your_table_files';
}
static get fields()
Optional
Default:
{
id: true,
path: true,
size: true,
name: true,
type: true,
dateCreated: true
}
This is used to indicate the fields of the files table/collection
static get fields() {
return {
...super.fields,
productId: true
};
}
SlsApiFileRelation
This Class extends from @janiscommerce/api
:warning: IMPORTANT, this API must be requested after making the upload to S3 Bucket.
API Example
// in src/api/item/file-upload/post.js
'use strict';
const { SlsApiFileRelation } = require('@janiscommerce/sls-api-upload');
const FileModel = require('../models/your-file-model');
class MyApiRelation extends SlsApiFileRelation {
get bucket() {
return 'bucket-name';
}
get model() {
return FileModel;
}
get entityIdField() {
return 'productId';
}
}
Request Data
This API has the following required request data:
- filename: (string) The name and extension of the file.
- filesSource: (string) The full key of the file stored in S3.
Request data example
{
"fileName": "front-image.png",
"fileSource": "files/images/1f368ddd-97b6-4076-ba63-9e0a71273aac.png"
}
Response
This API response with status-code 201
and id
if success to Save the file data Document.
// status-code 201
{
"id": "5e866d89fc33220011108188"
}
Getters
The following getters can be used to customize and validate your API:
get bucket()
Required
This is used to indicate the bucket where the file was saved
get bucket() {
return 'bucket-name';
}
get model()
Required
This is used to indicate the Model class that should be used to save the file relationship
const FileModel = require('../models/your-file-model');
get model() {
return FileModel;
}
get entityIdField()
Required
This is used to indicate the field name where the related entity ID should be saved
...
get entityIdField() {
return 'productId';
}
...
get customFieldsStruct()
Optional
This is used to indicate more fields to be validated from the request and saved with the relationship.
get customFieldsStruct() {
return {
myRelationshipCustomField: 'string',
myOptionalRelationshipCustomField: 'string?'
};
}
Request data example;
{
"fileName": "image.png",
"fileSource": "files/images/1f368ddd-97b6-4076-ba63-9e0a71273aac.png",
"myRelationshipCustomField": "theValue"
}
Hooks
This module has 2 Hooks:
- postValidateHook
- postSaveHook
postSaveHook(id, dataFormatted)
This hooks is async and execute after save the document. You can used it to emit an Event, invoke a Lambda function, create an extra Log, make a Request or whatever you need to the do after save.
postSaveHook(id, itemFormatted) {
return Invoker.call('ItemNotify', { id, ...itemFormatted});
}
Format
The object is created with the following fields:
name
: the filename, example:front-image.png
path
: the relative path in S3 Bucket, examplefiles/images/1f368ddd-97b6-4076-ba63-9e0a71273aac.png
mimeType
: the file full type, example:ìmage/png
type
: the simplified type, exampleimage
size
: the file size in Bytes, example:1000
But if you have more fields, or you can add any others, you can use a custom Format method
format(extraFileData)
It's async and received the extra file data (if you added customFieldsStruct
).
format({ myRelationshipCustomField, myOptionalRelationshipCustomField }) {
return {
relations: {
default: myRelationshipCustomField,
optional: myOptionalRelationshipCustomField
},
lucky: Math.random() * 1000
};
}
And final document saved in database would be:
{
path: 'files/images/1f368ddd-97b6-4076-ba63-9e0a71273aac.png',
name: 'front-image.png',
mimeType: 'image/png',
type: 'image',
size: 10000,
relations: {
default: 'stuff',
optional: 'accesory'
},
lucky: 667
}
SlsApiFileList
This API extends from @janiscommerce/api-list
API Example
// in src/api/item/file/list.js
'use strict';
const { SlsApiFileDelete } = require('@janiscommerce/sls-api-upload');
class MyApiList extends SlsApiFileList {}
In this example, the List API only can
- sort and filter by
id
: file-data document internal IDname
: filenamedateCreated
: strict mode* only search by exact Date
Also, every file-data document will NOT have a URL to use it for show it, download it, etc..
Custom Sorting and Filtering
If you need more fields to sort or filter exist 2 optionals getters.
get customSortableFields()
To add more fields to be sortable. Must return an Array of Strings
get customSortableFields() {
return ['type', 'order'];
}
get customAvailableFilters()
To add more fields to be sortable. Must return an Array of Strings or Object, see more in @janiscommerce/api-list filters.
get customAvailableFilters() {
return [
'type',
{
name: 'order',
valueMapper: Number
}
];
}
Adding the URL
If you want the file-data documents have an URL, for example because are images an you wanted to show them, you can added by changing this getter and adding an S3 bucket.
get shouldAddUrl()
Only must return a truthy value, by default is false
. If the bucket is not setted will fails with status-code 400
.
get shouldAddUrl() {
return true;
}
get bucket()
This is used to indicate the bucket where the file must be found.
get bucket() {
return 'bucket-name';
}
Format
You can format each file-data document and/or the file's URL.
formatFileData(fileData)
To format the file data except file-path
formatFileData({ order, ...fileData }) {
return {
...fileData,
order: `#${order}`
};
}
formatUrl(path)
By default it returns an URL signed to have access to S3 Bucket, which is add to url
field.
But if you wanted to changed this behaviour you can overwrigth it.
formatUrl(path) {
return `${this.bucket}/public/${path}`;
}
Hooks
This module has only one Hook:
SlsApiFileGet
This API extends from @janiscommerce/api-get
API Example
// in src/api/item/file/get.js
'use strict';
const { SlsApiFileGet } = require('@janiscommerce/sls-api-upload');
class MyApiGet extends SlsApiFileGet {
get bucket() {
return 'bucket-name';
}
}
URL field
This API module always return the file-data document with the url
field, so you must defined a S3 Bucket, otherwise it fails with status-code 400
.
get bucket()
Required
This is used to indicate the bucket where the file can be found.
get bucket() {
return 'bucket-name';
}
Format
The File-Document can be formatted in the same way as in the SLS-API-List using
Hooks
This module has only one Hook:
SlsApiFileDelete
This Class extends from @janiscommerce/api
API Example
// in src/api/item/file/delete.js
'use strict';
const { SlsApiFileDelete } = require('@janiscommerce/sls-api-upload');
const FileModel = require('../models/your-file-model');
class MyApiDelete extends SlsApiFileDelete {
get bucket() {
return 'bucket-name';
}
get model() {
return FileModel;
}
get entityIdField() {
return 'productId';
}
}
Getters
The following getters can be used to customize and validate your SlsApiFileDelete.
get bucket()
Required
This is used to indicate the bucket where the file is.
get bucket() {
return 'bucket-name';
}
get model()
Required
This is used to indicate the Model class that should be used to remove the file relationship
const FileModel = require('../models/your-file-model');
get model() {
return FileModel;
}
get entityIdField()
Required
This is used to indicate the field name where the related entity ID was saved
get entityIdField() {
return 'productId';
}
Hooks
This module has two Hooks:
- postValidateHook
- postDeleteHook
postDeleteHook(itemDeleted)
This hooks is async and execute after delete the document from S3 Bucket. You can used it to emit an Event, invoke a Lambda function, create an extra Log, make a Request or whatever you need to the do after delete it.
postDeleteHook(itemDeleted) {
return EventEmitter.emit({
entity: 'item',
event: 'deleted',
client: this.session.clientCode,
id: itemDeleted.id
});
}
5 months ago
8 months ago
11 months ago
11 months ago
11 months ago
11 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago