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

dc-api-core

v0.4.0-1

Published

Simple API core for your projects

Downloads

109

Readme

Simple API core for your projects

NPM

Useful links

Documentation image

Dependencies


Structure

📙
 ├── ⚙️ controllers      Request controllers
 ├── 🗃️ models           Models for working with DB
 │   └── 📁 <driver>     Database driver name (Optional)
 │       └── 📜 <model>  Model name (js or json)
 ├── ️📃 config.json      Configuration file
 └── ⏱ startup.js       Script, that was started before starting API server

Installation

0) Run npm init or yarn init

1) Install package - npm i dc-api-core --save or yarn add dc-api-core

2) Run npm exec dc-api-core init or yarn dc-api-core init

3) Run npm run dc-init or yarn dc-init

4) Run npm start or yarn start

5) Done!

CLI

You can use dc-api-core command locally in package.json scripts.

Options:

  • No options - Just running your project.
  • init - Create example files and start scripts.
  • --dev - Running project in development mode.
  • --cfg <path> - Overrides config.json location. You can use both relative and absolute paths.

config.json

| Field | Default | Description | |-----------------------|---------------------|------------------------------------------------------------| | db | Optional | Object | | db[driverName] | | Code of database driver | | db[driverName].name | Required | Database name | | db[driverName].port | Defined by plugin | Database port | | db[driverName].user | Optional | Database username | | db[driverName].pass | | and password | | db[driverName].srv | Optional for mongo | Boolean, true - use srv | | | | | | session.secret | Required | Private string for cookie | | session.store | Required | Database config name | | session.ttl | 3d (3 days) | Session lifetime in vercel/ms format, false - infinite | | | | | | ssl | Optional | Enables HTTPS mode if filled | | ssl.* | Optional | Any μWS.SSLApp options field | | ssl.key | Required | Local path to private key | | ssl.cert | Required | Local path to certificate file | | | | | | plugins | [] | Array of plugin packages names | | origin | Origin header | Accept requests only from this origin | | port | 8081 | API listing port | | ws_timeout | 60 | WebSocket request waiting timeout in seconds | | | | | | ignore | [] | Excluded directories in development mode | | isDev | Read-only | true if using --dev argument | | dev | {} | Config to merge if isDev is true | | ttl | 0 | WebSocket TTL in seconds, 0 - disabled |

Example:

{
    "port": "$env", // Equals value of process.env.PORT
    "db": {
        "mongo": {
            "host": "localhost",
            "name": "test-db"
        }
    },
    "plugins": ["dc-api-mongo"],
    "session": {
        "secret": "super secret string",
        "store": "mongo"
    },
    "ssl": {
        "cert": "/etc/letsencrypt/live/awesome.site/cert.pem",
        "key": "/etc/letsencrypt/live/awesome.site/privkey.pem"
    },
    "dev": {
        "port": 8081,
        "db": {
            "mongo": { "name": "test-dev-db" }
        }
    }
}

DB module

require('dc-api-core/DB'): {
    [string: code]: (config?: string, template?: Object) => DBDriver
}
  • code - Registered code of database driver. For example dc-api-mongo registers mongo.
  • config - Configuration name after dot in config.json. Ex. mongo('dev') points to db['mongo.dev'].
  • template - Object that overrides selected configuration.
  • DBDriver - Mongoose-like object (not always, defined by plugin)

Example:

const db = require('dc-api-core/DB').mongo();

Where mongo - your database driver name.

Example: If you're using MySQL, use mysql as database driver (don't forget to apply plugin first).

const db = require('dc-api-core/DB').mysql();

Plugins

For first, install plugin package via npm or yarn. After this add name of plugin package to plugins array in config.json.

Example config.json:

{
    // ...
    "plugins": ["dc-api-mongo"]
}

If you want create your own plugin, read plugin development documentation


Sessions

Functions

| Function | Example | Description | |--------------------------|--------------------------------|------------------------| | this.session.<name> | this.session.name = 'User' | Set session data | | this.session.save() | await this.session.save() | Save session data | | this.session.destroy() | await this.session.destroy() | Clear all session data |

Example

module.exports = class Controller {
    async test () {
        this.session.name = 'test';
        await this.session.save();
        this.send('saved');
    }
}

Request hooks

onLoad

Will be executed before calling action method in controller.

If the onLoad function returns false, the request will be rejected.

Example

module.exports = class Test {
    onLoad () {
        if (!this.session.user) return false;
    }
}

Working with config.json

Require

Require config module:

const config = require('dc-api-core/config');

Get data:

config.<your_param>

Example

const config = require('dc-api-core/config');

module.exports = class Test {
    index() {
     this.send(config.myParam);
    }
}

Routing

Register route in startup script:

// startup.js
const Router = require('dc-api-core/router');
Router.register('/testing/files/${id}/${file}.jpg', 'Test.getFile');

Now requests like /testing/files/some-id/secret_file.jpg will call getFile method of Test controller.

// controllers/Test.js
class Test {
    async getFile () {
        this.send(this.params);
        // Will send { "id": "some-id", "file": "secret_file" }
    }
}

module.exports = Test;

My TODOs

  • [ ] Document new config.cors.headers

  • [ ] Support for glibc < 2.18

  • [ ] Typing (.d.ts) files

  • [ ] Automatic package publication when all tests are passed

  • [ ] More functionality tests

  • [ ] Clusterization/multi-threading support

  • [ ] Edit pages "API" > "Database driver" and "Plugins" > "Basics" of docs

  • [ ] Repair CLI