npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@knovator/pagecreator-node

v1.2.2

Published

PageCreator Node.js module

Downloads

524

Readme

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

| Code | Description | | -------------- | -------------------------------------------------------------------------------------- | | title | Title of collection name to show in UI | | collectionName | Collection name specified in database | | filters | Filter object to apply while getting data, like { isDeleted: false, isActive: true } | | searchColumns | Array of fields to to perform search | | aggregations | Array of aggregation items you want to apply while retriving items | | customWidgetTypes | Array 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

| Code | Description | | ------- | ------------------------------------ | | SUCCESS | When request fullfiled without error | | ERROR | When request fullfiled with error |

Custom Validation messages

| Message | Description | | ---------------------------------- | ----------------------------------------------- | | Widget with same code is available | When widget with same code is exist in database |

HTTP Status Codes

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

Routes

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

Widget

| Route | Method | Description | | ------------------ | ---------- | -------------------------------------------------------- | | /widget-types | GET | Get widget-types like Image and provided collections | | /selection-types | GET | Get Selection types like Fixed Card and Carousel | | /list | POST | List widget data in pagination | | / | POST | Create widget | | /:id | PUT | Update widget | | /:id | PATCH | Partial Update widget | | /:id | DELETE | Delete widget whose id send in body | | /collection-data | POST | Get collection data |

Page

| Route | Method | Description | | ------- | ---------- | ----------------------------------- | | /list | POST | List page data in pagination | | / | POST | Create page | | /:id | PUT | Update page | | /:id | DELETE | Delete page whose id send in body |

User

| Route | Method | Description | | -------------- | -------- | -------------------------------------------------------- | | /widget-data | POST | Get widget-data data for specified widget code in body | | /page-data | POST | Get 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);

| CODE | Description | | -------------------------- | ------------------------------------------------------------ | | widget.getItemsTypes | While fetching widget types | | widget.getWidgetTypes | While fetching selection types | | widget.getAll | While fetching widgets | | widget.create | While creating widget | | widget.update | While updating widget | | widget.partialUpdate | While doing partialUpdate for widget, like toggle IsActive | | widget.delete | While deleting widget | | widget.getCollectionData | While getting widget collection-data | | page.getAll | While getting pages in pagination | | page.create | While creating page | | page.update | While updating page | | page.delete | While deleting page | | user.widgetNotFound | While widget is not found | | user.pageNotFound | While page is not found | | user.getWidgetData | While getting widget data | | user.getPageData | While 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