KleeenAPI
Getting started
- Add a folder at the root level called
kleeenApi
. - Create an
entities.json
Here the endpoint user will be created:
[
{
"name": "users",
"description": "Users desc",
"initialQuantity": 50,
"excludeHttpMethods": [],
"properties": {
"username": {
"type": "username",
"description": "prop description",
"required": true
},
}
}
]
How to add custom endpoints
- Under the
kleeenApi
folder add theendpoints.js
file. - Map the entity name to the new api.
Example:
Let say you have an entity called os_users
in the entities.json
.
{
"name": "os_users",
//...
}
So, you can redirect the traffic of that entity to the one specified in the endpoints.js
file:
module.exports = {
os_users: 'http://this_is_an_external_api:64211/os_users_external',
};
Adding it to another project
- Add the
@kleeen/kui-cli
package to your project. - Add the required files under the
kleeenApi
folder.
Generate the data by running:
kui-cli generate kapi
Run it by executing:
kui-cli run kapi
Dev Mode
In order to run KleeenAPI locally
-
Build the code
npm run build
-
Run the server
npm run dev
Pagination
Use _page
and _limit
to paginate through the data.
Use _limit
to control the number of returned items per page, the fault is 10.
The X-Total-Count
and X-Result-Count
headers are available to play with.
GET /users?_page=1&_limit=5
Data Filtering
Kleeen API allows to perform several operations on the data, these are some examples:
GET /users?username=Borer_Aylin
GET /users?username=Borer_Aylin&address=some
GET /users?q=Ella
GET /users?username_like=Borer
GET /users?username_ne=Borer_Aylin
GET /users?version_gte=Borer_Aylin
GET /users?_sort=username&_order=asc
GET /users?_sort=username,device&_order=asc,desc
KAPI Combine
KAPI Combine allows to combine several request into one.
POST `/kapi_combine`
{
"widgetUsers": {
"resolve": "users",
"queryParams": {
"_sort": "username",
"_order": "asc",
}
},
"userDevices": {
"resolve": "devices"
},
"osUsers": {
"resolve": "users",
"queryParams": {
"id": "f30c2bc7-d2f9-45ac-9d2b-889aa0e313d0"
}
}
}
Scheduler
Allows to schedule reminders.
Create a new schedule
To create a new reminder you can do a POST
to /schedule/:clientId
being clientId
the unique identifier of the client.
The payload of that request is as follows:
name: The name of the reminder.
scheduleOn: A human readable interval; it uses date.js to create the interval, some examples are:
- 10 minutes
- 5pm tonight
- tomorrow at noon
- next week tuesday
- next week tuesday at 4:30pm
- 2 weeks from wednesday
- tomorrow night at 9
- this morning at 9
- at 12:30pm
endAfter: The number of iterations a schedule will be run. If -1
is provided it means the job will run forever or until it is stop.
Examples
It will schedule a reminder every day at 8 am
POST `/schedule/my-unique-client-id`
{
name: "send morning email",
scheduleOn: "this morning at 8",
endAfter: -1
}
It will schedule 3 occurrences of the event at 5 pm.
POST `/schedule/my-unique-client-id`
{
name: "sync-users-table",
scheduleOn: "5pm tonight",
endAfter: 3
}
How to listen for events
When a job is created the /schedule
path will be used; so, let's say a job with the id send morning email
was created, this is how you should listen for that event:
import io from 'socket.io-client';
// Here you provide the clientId.
const socket = io('http://localhost:3001/schedule', { query: { client_id: 'my-unique-client-id' } });
socket.on('send morning email', ({ type }) => {
if(type === 'notify') {
// Send the morning email only when the scheduled time has arrived.
sendMorningEmail();
}
});
The socket's payload is:
{
id: "my-unique-client-id:send morning email",
type: "notify"
}
The type
could be:
- error: an error ocurred
- notify: when the schedule time has arrived.
- resume: on resume.
- pause: on pause
- stop: the the schedule has finished or when it is manually stopped.
More API controls
Job Status
get /schedule/:clientId/:scheduleId
Remove
delete /schedule/:clientId/:scheduleId
Pause
patch /schedule/:clientId/:scheduleId/pause
Resume
patch /schedule/:clientId/:scheduleId/resume
Extended configuration
KleeenAPI provides a default configuration that can be extended by using these env
variables:
-
KAPI_AUTO_SAVE_INTERVAL
- The number of milliseconds that must pass to persist the data in the kapi.db. Default to
4000
, each 4 seconds. IfKAPI_DB_TYPE=in-memory
this does not have effect.
- The number of milliseconds that must pass to persist the data in the kapi.db. Default to
-
KAPI_PORT
- The port to be used by the API. The default is 3000.
-
KAPI_PORT_WS
- The port to be used by the WebSockets. The default is 3001.
-
KAPI_BASE_FOLDER
- The base folder path were the kapi assets are going to be stored.
- Relative to the running kapi instance.
-
KAPI_ROUTES_PATH
- The path were the custom routes files are going to be stored.
- It overrides
KAPI_BASE_FOLDER
.
-
KAPI_DB_PATH
:- The path were the
db
files are going to be stored. - It overrides
KAPI_BASE_FOLDER
.
- The path were the
-
KAPI_DB_TYPE
-
local
: (default) it creates the files to store the generated data. -
in-memory
: the generated data is always in memory.
-
-
KAPI_SKELETON_TYPE
-
local
: (default) it creates an skeleton file that describes the API. -
in-memory
: the file is not created.
-
-
KAPI_FIND
:-
flexible
: it will return a random item when the id does not exists.
-
Configuration file
You can provide your own file with the configuration.
By default it reads the kapi.json
at the root of the folder
For a custom file, use it with kleeen-cli
by adding the -config=
arg.
kui-cli run kapi -config=/Users/jhon/data/temp/config.json
{
"apiPort": 3000,
"apiPortWS": 3001,
"autoSaveInterval": 4000,
"isFlexibleFind": false,
"isInMemory": false,
"isSkeletonInMemory": false,
"dbPath" : "/Users/jhon/data/temp",
"basePath": "kleeenApi",
"routesPath": "kleeenApi/routes"
}
Paths
The default folder for the paths is kleeenApi
.
Aggregation functions
Group by department and count the results
get /departments?_grouped_by=name&_aggregation_attribute=name&_aggregation=count
KleeenAPI data types
// Address
country // 'United Kingdom'
city // 'New Ortiz chester'
zip(digits = {5, 9}) // '26995-7979' (if no digits specified then random selection between ZIP and ZIP+4)
street // 'Jadyn Islands'
address // '6390 Tremblay Pines Suite 784'
address1 // '8417 Veda Circles'
address2 // 'Suite 648'
state // 'Michigan'
state_abbr // 'CO'
latitude // 90.0610
longitude // 180.0778
building_number // 2413
// Text
sentence // 'Laborum eius porro consequatur.'
sentences(n = 3) // 'Dolorum fuga nobis sit natus consequatur. Laboriosam sapiente. Natus quos ut.'
title // 'Systematic nobis'
text // 'Nemo tempore natus non accusamus eos placeat nesciunt. et fugit ut odio nisi dolore non ... (long text)'
description // 'Vel et rerum nostrum quia. Dolorum fuga nobis sit natus consequatur.'
short_description // 'Qui iste similique iusto.'
string // 'saepe quia molestias voluptates et'
word // 'voluptatem'
words(n = 7) // 'sed quis ut beatae id adipisci aut'
array_of_words(n = 7) // [ 'voluptas', 'atque', 'vitae', 'vel', 'dolor', 'saepe', 'ut' ]
letter // 'k'
// Internet
ip // '21.44.122.149'
ipv6 // 'c36d:f839:37ea:6ccd:ccba:d72a:d991:1c4d'
domain // 'darrion.us'
url // 'germaine.net'
email // 'Josue.Hessel@claire.us'
user_agent // 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0'
// Person
name // 'Alberto'
username // 'Darryl'
first_name // 'Derek'
last_name // 'Considine'
full_name // 'Kadin Torphy'
password // '(205)580-1350Schumm'
name_prefix // 'Miss'
name_suffix // 'Jr.'
company_name // 'Cole, Wuckert and Strosin'
company_suffix // 'Inc'
catch_phrase // 'Synchronised optimal concept'
phone // '982-790-2592'
// Numbers
random // 0.7171590146608651 (core generator)
integer(from = -1000, to = 1000) // 632
double(from = -1000, to = 1000) // -234.12987444
array_of_digits(n = 7) // [ 4, 8, 3, 1, 7, 6, 6 ]
array_of_integers(n = 7) // [ -105, -7, -532, -596, -430, -957, -234 ]
array_of_doubles(n = 7) // [ -866.3755785673857, -166.62194719538093, ...]
coin_flip // true
// Date
unix_time // 659897901
moment // moment.js object see http://momentjs.com/docs/
date(format = 'YYYY-MM-DD') // '2001-07-06' (see available formatters http://momentjs.com/docs/#/parsing/string-format/)
time(format = 'HH:mm:ss') // '03:08:02' (see available formatters http://momentjs.com/docs/#/parsing/string-format/)
century // 'IV'
am_pm // 'am'
day_of_year // 323
day_of_month // 9
day_of_week // 4
month_number // 9
month_name // 'March'
year // 1990
timezone // 'America/Miquelon'
timestamp // 1575912457506
// Payments
card_type // 'American Express'
card_number(vendor) // '4716506247152101' (if no vendor specified then random)
card_exp // '03/04'
card_data // { type: 'MasterCard', number: '5307558778577046', exp: '04/88', holder_name: 'Jaron Gibson' }
// Misc
country_code // 'ES'
language_code // 'ru'
locale // 'hi_IN'
currency // { symbol: 'R', name: 'South African Rand', symbol_native: 'R', decimal_digits: 2, rounding: 0, code: 'ZAR', name_plural: 'South African rand' }
currency_code // 'TRY'
currency_symbol // 'TL'
currency_name // Turkish Lira
mime_type // 'audio/mpeg'
file_extension // 'rtf'
boolean // true
uuid // '2f4dc6ba-bd25-4e66-b369-43a13e0cf150'
// Colors
color_name // 'DarkOliveGreen'
safe_color_name // 'maroon'
rgb_hex // '#2e4e1f'
rgb_array // [ 194, 193, 166 ]
rgba // 'rgba(194, 193, 166, 0.5)
rgba_array // [ 194, 193, 166, 0.5 ]
rgba_hex // '#2fd0ddce'
Images
Parameters: width
, height
, category
Generates a Url link to lorempixel
http://lorempixel.com/400/500
image
avatar
image.abstract
image.animals
image.business
image.cats
image.city
image.food
image.nightlife
image.fashion
image.people
image.nature
image.sports
image.technics
image.transport
identicon
- Base64 svg
Parameters
-
key
: preservers the identicon. -
size
: the size of the identicon.
identicon