emperjs

1.4.10 • Public • Published

emperjs

A framework to make a http and https webserver. Has build in an api router and register.
npm i emperjs
const createServer = require("emperjs");
const Server = createServer("https");
const server = new Server();
// or
const Server = require("emperjs")("http");
const server = new Server();

createServer(protocol[, options])

    protocol <string> Default: "http"
    The protocol is "http" or "https". The factory created class Server extends dynamically from the protocol's Server class.
    options <Object> optional
      logger <Boolean>
      If false the server does not log when the request starts and when the response ends.
    Returns <Server>
    Creates a Server class.
Creates a Server class. The Server is described below.

Class: Server

new Server()

server.listen(options)

    options <Object>
      port <integer> Default: 8080
      hostname <string> Default: "127.0.0.1"
      listeningListener <Function>
      function listeningListener() {}
      The callback that is invoked when the server is listening.
    Returns this <Server>
    Allows chaining methods.
Starts the webserver listening for connections.

server.delete(path, callback[, options])

<HTTP method>
Places the callback as a DELETE method at the specified path.

server.get(path, callback[, options])

<HTTP method>
Places the callback as a GET method at the specified path.

server.head(path, callback[, options])

<HTTP method>
Places the callback as a HEAD method at the specified path.

server.options(path, callback[, options])

<HTTP method>
Places the callback as a OPTIONS method at the specified path.

server.patch(path, callback[, options])

<HTTP method>
Places the callback as a PATCH method at the specified path.

server.post(path, callback[, options])

<HTTP method>
Places the callback as a POST method at the specified path.

server.put(path, callback[, options])

<HTTP method>
Places the callback as a PUT method at the specified path.

HTTP methods:

    path <string>
    Variable parameters are indicated by a forward slash folllowed by a colon, such as /:param1. Parameters are added to the request.params object.
    callback <Function> function callback(request, response) {}
      request <Request>
      An instance of the class from the Server.IncomingMessage.
      response <Response>
      An instance of the class from the Server.ServerResponse.
    options <Object> optional
      record <Boolean>
      If set to false it is excluded in the ApiRegister and no record is reported to.
An incomming request that has found it's route to the path and the corresponding HTTP method invokes the callback. If the request's path does not exist the response return with status 400 and specifies which part of the path was not identified, else if the request's HTTP method does not exist the response return with status 405 method not allowed.

server.use(path, callback)

    path <string>
    Variable parameters are indicated by a forward slash folllowed by a colon, such as /:param1. Parameters are added to the request.params object.
    callback <Function> function callback(request, response, next) {}
      request <Request> Required!
      An instance of the class from the Server.IncomingMessage.
      response <Response> Required!
      An instance of the class from the Server.ServerResponse.
      next <Function> Required!
      function next() {}
      The argument next is a function and must be invoked in order to reach the endpoint.
Inserts middleware functions at the specified path. Requests at the specified path or requests having crossed the specified path are using the middleware. Middleware functions are invoked before the api endpoint is invoked.

server.loadApiRegister(register, reset)

    register <Object>
    Throws a TypeError when register is not an object.
    reset <Boolean>
    If reset is true sets every endpoint's counter and bytes property to 0.
    Returns this <Server>
    Allows chaining methods.
Loads an external object to replace the server's apiRegister.

server.destroyUnusedRecords()

    Returns this <Server>
    Allows chaining methods.
Destroys any ApiRecord that does not exist in a route.

server.apis

Readable property of the apiRegister's apis property.

Server.IncomingMessage

Static readable and writable property of the server's IncomingMessage class. This property can only be set by a class that is extended at least by the base class. If the property is set with the value null it is restored back to the class Request.

Server.ServerResponse

Static readable and writable property of the server's ServerResponse class. This property can only be set by a class that is extended at least by the base class. If the property is set with the value null it is restored back to the class Response.

Server.Socket

Static readable and writable property of the server's Socket class. This property can only be set by a class that is extended at least by the base class. If the property is set with the value null it is restored back to the class Socket.

Server.ApiRecord

Static readable and writable property of the ApiRegister's ApiRecord class. This property can only be set by a class that is extended at least by the base class. If the property is set with the value null it is restored back to the class ApiRecord.

Server.logger

Static readable property of the Server's logger instance.

Server.mimetypes

Static readable and writable property of the Server's mimetypes. These mimetypes are used at the method response.sendFile to identify a file's extension with the corresponding mimetype.

Class: Socket

This object is created internally by the server in the earliest stage of an incomming request right before the server's connection event is fired. The class Socket can be read from the static property Server.Socket. It can be also be overwritten as long as the value is a class that was extended from Socket.

Class: Request

This object is created internally by the server. It is passed as the first parameter to any endpoint's function. It may be used to access response status, headers and data. The class Request can be read from the static property Server.IncomingMessage. It can be also be overwritten as long as the value is a class that was extended from Request.

request.body

Property where the request's parsed body is placed in. The body is parsed by an individual requestBodyParser.

request.params

Property where the request's path parameters are placed in. If the path to an API was "/path/to/:param1/and/:param2" and a request has a path of "/path/to/aapje/and/12345" then the params would become { param1: "aapje", param2: "12345" }.

request.urlSearchParams

Property where the request's search parameters are placed in. The url search parameters are parsed by Node JS's build-in class URLSearchParams. When the request has a path of "/path/to/api?param1=aapje&param2=01234&param2=56789" then the request.urlSearchParams.getAll("param2") would return ["01234", "56789"].

Request.bodyParsers

Static readable property of the Request's bodyParsers instance. Contains individual requestBodyParser.

Class: Response

This object is created internally by the server. It is passed as the second parameter to an endpoint's function. The class Response can be read from the static property Server.ServerResponse. It can be also be overwritten as long as the value is a class that was extended from Response.

response.sendJson(status, data)

Sends a json object back to the response. This method invokes writeHead with status set to 200 and the headers content-type set to "application/json" and invokes the send method.

response.send(data)

Invokes the response's end and the report method.

response.sendError(status, error)

Uses the Server's logger.error method to log the error.stack, invokes writeHead with status and the headers content-type set to "text/plain" and invokes the end method with an error.message.

response.sendFile(filepath)

    filepath <String>
    If a file does not exist at filepath the response's sendError is invoked with status 404.
    Returns this <Response>
    The response is returned to allow chain invoking multiple calls to sendFile.
Invoke this method to stream files to the response. The response content-type header are set to the mimetype found from the file that was send, unless the content-type header was already set. If the mimetype was not found within the static property Server.mimetypes the response content-type header is set to "text/plain". In a single response invoking sendFile more than once results in these files to be appended as one file and send in chunks to the response. This is not the same as creating templates of files but it can provide similair results. A CallbackQueue ensures that the files are send sequentially. The last call that is not followed by another call to sendFile ends the response.
The method sendFile is build to reduce the amount of memory allocated for storing Buffer's while streaming. The first optimization is that a single readable file can attach an x number of writable contexts. The second optimization is that a single writable context can attach an x number of responses. As the readable file reads chunks <Buffer> from a file, those chunks are send to all responses that were attached to the writable context. That means that when 10 responses have been attached to a single writable context there will be 9 fewer chunks of 16kb in memory. The life cycle of reading a file is open > stat > read > close. Getting the stat from a file is only used to get the byte-length of a file but this operation consumes more time than the open read and close operations. The readable file recycles the same file-descriptor and byte-length and while there is still a writable context attached, new writable contexts attaching keep the readable file open.

response.apiRecord

Readable property of the apiRecord for the endpoint.

Class: RequestBodyParsers

The requestBodyParsers is read from the static property bodyParsers from the Request class.

requestBodyParsers[mimetype]

Readable properties containing a requestBodyParser.

requestBodyParsers.add(mimetype, parse[, errorMessage])

    mimetype <String>
    A requestBodyParser is accessed by using the mimetype as locator.
    parse <Function>
    function parse(body) {}
    This requestBodyParser uses this parse function in order to parse data from incomming requests and put the parsed data in request.body. These parse functions wrapped in a try catch.
    errorMessage <String> Optional
    In case the parse function got an error when parsing this errorMessage is send to the response with the method request.sendError, otherwise the error that was catched by the parser itself is send.
    Returns this <RequestBodyParsers>
    Allows chaining methods.
Use this method to add a new requestBodyParser. By default requestBodyParsers exist for content-type "application/json" that parses with JSON.parse and for content-type "application/x-www-form-urlencoded" that parses with URLSearchParams.

Class: ApiRecord

Every HTTP method published is stored in the Server's ApiRegister as an ApiRecord. Every apiRecord stores and updates information from the server's endpoints. This class can be read from the static property Server.ApiRecord.

apiRecord.report(byteLength)

Each endpoint is recorded in an ApiRecord from the Server's ApiRegister. Invoking report increments the apiRecord's counter property and adds the byteLength to the apiRecord's bytes property.

apiRecord.reset()

This method sets counter and bytes properties to 0.

apiRecord.counter

This porperty is used to count the amount of times a request has successfully responded. It does not increment when the response's sendError method is invoked.

apiRecord.bytes

This property is used to update the amount of bytes written from the server to clients.

Class: Logger

An instance from this class is exported and required throughout the Server's library. The instance can be read from the static property Server.logger.

logger.log

Readable and writable property for the log function. If set with a value that is not a function an error is thrown.

logger.error

Readable and writable property for the error function. If set with a value that is not a function an error is thrown.

Readme

Keywords

none

Package Sidebar

Install

npm i emperjs

Weekly Downloads

2

Version

1.4.10

License

ISC

Unpacked Size

67.2 kB

Total Files

15

Last publish

Collaborators

  • burndkemper