1.0.0 • Published 22 days ago

@knovator/pagecreator-node v1.0.0

Weekly downloads
-
License
-
Repository
github
Last release
22 days ago

Contributors Forks Stargazers Issues MIT License

About The Project

@knovator/pagecreator-node is built with intent to build pages that are depend on backend data, and admin can change how page will look like.

Built With

Getting Started

To integrate @knovator/pagecreator-node, you should be having basic nodejs application up and running with express (optionally using mongoose for mongodb database). @knovator/pagecreator-node provides routes for widget, page and user to use in application.

Prerequisites

  • It's good start to have nodejs application up and running with express. Good to have used i18next to add message in response codes.
  • routes uses mongoose connection established by application, so it's required to connect to database before using package. For example,

    // db.js
    const mongoose = require('mongoose');
    
    mongoose
      .connect('mongodb://localhost:27017/knovator')
      .then(() => console.info('Database connected'))
      .catch((err) => {
        console.error('DB Error', err);
      });
    
    module.exports = mongoose;
  • Image upload route for upload & remove is needed to declare externally. Example,

    // fileRoute.js
    const express = require('express');
    const router = express.Router();
    
    router.post(`/files/upload`, (req, res) => {
      // TO DO: some file storage operation
      let uri = '/image.jpg';
      let id = '62c54b15524b6b59d2313c02';
      res.json({
        code: 'SUCCESS',
        data: { id, uri },
        message: 'File uploaded successfully',
      });
    });
    
    router.delete(`/files/remove/:id`, (req, res) => {
      // TO DO: some file remove operation
      res.json({
        code: 'SUCCESS',
        data: {},
        message: 'File removed successfully',
      });
    });
    
    module.exports = router;

Sample App file

require('./src/db');
require('./src/models/file');

const cors = require('cors');
const express = require('express');
const fileRoutes = require('./fileRoute.js');
const PORT = 8080;

const app = express();
app.use(cors());
app.use(express.static('public'));
app.use(fileRoutes);

// ...
app.listen(PORT, () => {
  console.log(`App started on ${PORT}`);
});

Installation

  1. Add pagecreator package,
    npm install @knovator/pagecreator-node
    # or
    yarn add @knovator/pagecreator-node

Usage

App/Main file is a good place to use @knovator/pagecreator-node

const {
  setConfig,
  WidgetRoutes,
  ItemRoutes,
  FileUploadRoute,
  PageRoutes,
  UserRoutes,
} = require('@knovator/pagecreator-node');

setConfig({
  collections: [
    {
      title: 'Notifications',
      collectionName: 'notifications',
      filters: { isDeleted: false, isActive: true },
      searchColumns: ['name', 'code'],
    },
  ],
});

app.use('/widgets', WidgetRoutes);
app.use('/items', ItemRoutes);
app.use('/media', FileUploadRoute);
app.use('/pages', PageRoutes);
app.use('/users', UserRoutes);

app.listen(PORT, () => {
  console.log(`App started on ${PORT}`);
});

Through setConfig function e can set logger, collections and catchAsync functions as parameters. By collections, we can add reference of application collections.

  • handleUpdateData is used to handle update redis cache when data is updated in database. It takes collectionName and _id as parameters.

      import { handleUpdateData } from '@knovator/pagecreator-node';
    
      handleUpdateData('notifications', '62c54b15524b6b59d2313c02');

parameter explanations

  • logger
    • Provides ability to add logging for Database and Validation
      // default
      console;
  • catchAsync
    • Wraps functions to handle async errors
      // default
      function catchAsync(fn) {
        return function (req, res, next) {
          Promise.resolve(fn(req, res, next)).catch((err) => {
            // this.logger.error(err.message);
            res.status(internalServerError).json({
              code: RESPONSE_CODE.ERROR,
              message: err.message,
              data: {},
            });
          });
        };
      }
  • collections
    • Array of collection items to add reference of collections in package.
  • redis

    • Redis URL string or connection object to wrap user APIs into redis cache.
    • i.e. redis://localhost:6379 or { HOST: 'localhost', PORT: 6379, PASSWORD: "test", USER: "test", DB: 0 }

Collection Item Format

CodeDescription
titleTitle of collection name to show in UI
collectionNameCollection name specified in database
filtersFilter object to apply while getting data, like { isDeleted: false, isActive: true }
searchColumnsArray of fields to to perform search
aggregationsArray of aggregation items you want to apply while retriving items
customWidgetTypesArray of widget types to add, like { label: "", value: "", imageOnly: true, collectionsOnly: true; }

Example,

setConfig({
  collections: [
    {
      title: 'Notifications',
      collectionName: 'notifications',
      filters: { isDeleted: false, isActive: true },
      searchColumns: ['name', 'code'],
      aggregations: [
        {
          $lookup: {
            from: 'file',
            let: {
              id: '$fileId',
            },
            pipeline: [
              {
                $match: {
                  $expr: {
                    $eq: ['$_id', '$$id'],
                  },
                },
              },
              {
                $project: {
                  _id: 1,
                  nm: 1,
                  uri: 1,
                  mimeType: 1,
                },
              },
            ],
            as: 'fileId',
          }
        },
        {
          $project: {
            _id: 1,
            nm: 1,
            fileId: 1,
          }
        },
        {
          $match: {
            deletedAt: { $exists: false },
          }
        }
      ]
    },
  ],
});

Routes Infomration

Response follows following structure

{
  code: RESPONSE_CODES,
  message: "" // if internationalized is applied
  data: {}
}

Response Codes

CodeDescription
SUCCESSWhen request fullfiled without error
ERRORWhen request fullfiled with error

Custom Validation messages

MessageDescription
Widget with same code is availableWhen widget with same code is exist in database

HTTP Status Codes

HTTPDescription
200When request fullfiled without error
201When document is created
500When internal server occurred
422When Validation error occurred
404When Resource is not found

Routes

This are the routes that gets integrated by @knovator/pagecreator-node,

Widget

RouteMethodDescription
/widget-typesGETGet widget-types like Image and provided collections
/selection-typesGETGet Selection types like Fixed Card and Carousel
/listPOSTList widget data in pagination
/POSTCreate widget
/:idPUTUpdate widget
/:idPATCHPartial Update widget
/:idDELETEDelete widget whose id send in body
/collection-dataPOSTGet collection data

Page

RouteMethodDescription
/listPOSTList page data in pagination
/POSTCreate page
/:idPUTUpdate page
/:idDELETEDelete page whose id send in body

User

RouteMethodDescription
/widget-dataPOSTGet widget-data data for specified widget code in body
/page-dataPOSTGet page-data data for specified page code in body

descriptor codes & i18n code for messages

Nextjs i18n package adds facility for internationalization in nodejs application, and it's used in following manner

// usage
req?.i18n?.(CODE);
CODEDescription
widget.getItemsTypesWhile fetching widget types
widget.getWidgetTypesWhile fetching selection types
widget.getAllWhile fetching widgets
widget.createWhile creating widget
widget.updateWhile updating widget
widget.partialUpdateWhile doing partialUpdate for widget, like toggle IsActive
widget.deleteWhile deleting widget
widget.getCollectionDataWhile getting widget collection-data
page.getAllWhile getting pages in pagination
page.createWhile creating page
page.updateWhile updating page
page.deleteWhile deleting page
user.widgetNotFoundWhile widget is not found
user.pageNotFoundWhile page is not found
user.getWidgetDataWhile getting widget data
user.getPageDataWhile getting page data

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

Distributed under the MIT License. See LICENSE.txt for more information.

Contact

Knovator Technologies

Project Link: https://github.com/knovator/pagecreator

1.0.0

22 days ago

0.9.7

2 months ago

0.8.8

9 months ago

0.9.4

8 months ago

0.9.3

9 months ago

0.9.6

8 months ago

0.8.7

10 months ago

0.9.0

9 months ago

0.8.6

12 months ago

0.8.5

1 year ago

0.7.6

1 year ago

0.8.4

1 year ago

0.7.5

1 year ago

0.8.1

1 year ago

0.8.0

1 year ago

0.8.3

1 year ago

0.7.4

1 year ago

0.8.2

1 year ago

0.7.3

1 year ago

0.7.2

1 year ago

0.7.1

1 year ago

0.7.0

1 year ago

0.3.0

1 year ago

0.2.0

1 year ago

0.5.4

1 year ago

0.5.3

1 year ago

0.5.6

1 year ago

0.5.5

1 year ago

0.5.0

1 year ago

0.4.0

1 year ago

0.5.2

1 year ago

0.6.0

1 year ago

0.5.1

1 year ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago