Guardflux
A light callable lib to keep your Node.Js API alive
Installation
npm i guardflux
Functions and usage
schema
This is expansion of Joi lib that we use it to verify API input. It can be query
or body
of a request. Here is the example of usage:
const ipSchema = schema.object({
api_key: schema.string().min(10).max(10).required(),
})
checkObject()
Then you can verify the input with checkObject()
function and it returns result with two elements isValid: boolean
and log: any
. isValid
returns true
if given object and schema match and log
returns Joi
log if an error happen. Also this function has an element called devMode
that prints all logs in console
to get what is happening in function and defult setted to true
. Here is the full example:
import { checkObject, schema } from 'guardflux'
import { CheckResult } from 'guardflux/dist/lib/types'
...
const user_given_api_key: string = "x2a45B78C0"
const ipSchema = schema.object({
api_key: schema.string().min(10).max(10).required(),
})
const check: CheckResult = await checkObject({ api_key: user_given_api_key }, ipSchema)
You can use check.isValid
to response the user that given data in request is valid or not.
rateLimit()
This is a very useful fucntion that make rate limit for every route based on user api-key/id/ip that you pass. We use MikroOrm because it is light and can handle several DBs. Because of needing to save data in DB we have to config the DB options first:
const dbConfig: DbConfig = {
dbName: "guardflux",
dbType: "mongodb",
dbURI: MONGO_URI,
dbDebug: true
}
If your DB has username and password, you can add it to you URI string. These are default DBs URI string that don't have username and password.
Type | default connection url |
---|
mongo | mongodb://127.0.0.1:27017 |
mysql | mysql://root@127.0.0.1:3306 |
postgresql | postgresql://postgres@127.0.0.1:5432 |
After we config the DB, we have to add options
for rateLimit
function:
const rlOptions: RateLimitOptions = {
route: "/api/test_route",
cycleTime: 60,
maxRequests: 5
}
Now we pass all consts to function. This function works based on two keys: 1- User API-key/ip/id 2- Route path. At least you can turn devMode
to see in console what is happen. Like checkObject
function, this method has devMode
too that is enabled by default.This option will prints all data of MikroOrm
and what is happen in function. This function returns like checkObject
and you can use it to response the user if you want. All example is here:
import { checkObject, schema } from 'guardflux'
import { CheckResult } from 'guardflux/dist/lib/types'
...
const user_given_api_key: string = "x2a45B78C0"
const rlOptions: RateLimitOptions = {
route: "/api/test_route",
cycleTime: 60,
maxRequests: 5
}
const dbConfig: DbConfig = {
dbName: "guardflux",
dbType: "mongodb",
dbURI: MONGO_URI,
dbDebug: true
}
const rl: CheckResult = await rateLimit(user_given_api_key, rlOptions, dbConfig)
License
This project is licensed under the MIT License - see the LICENSE file for details.