sgapps-server

SGApps Network Server

Usage no npm install needed!

<script type="module">
  import sgappsServer from 'https://cdn.skypack.dev/sgapps-server';
</script>

README

SGApps Server

pipeline status License ยป Creative Commons Attribution-NonCommercial 4.0 / or Granted by SGApps Labs Repository - GitLab Documentation Sergiu Gordienco email sergiu.gordienco@gmail.com

npm GitHub package.json version (branch) GitHub issues GitHub pull requests

A network solution for web applications.

Since this application is fully compatible with nodejs-mvc, I decided to replace nodejs-mvc with this new approach. SGApps Server is completely new solution, that will be improved continuously thats why I will work on this project instead of nodejs-mvc

by Sergiu Gordienco < sergiu.gordienco@sgapps.io >

Authors

  • Gordienco Sergiu < sergiu.gordienco@sgapps.io >

License

the license is Apache-2.0

Full documentation can be found on Documentation

API

Table of Contents

SGAppsServerRequestSession

Type: function (request, options)


_created

Type: number


_ip

Type: string


_confirmed

Session was received from previously saved cookie

Type: boolean


_id

Type: string


_options

Type: SGAppsSessionManagerOptions


data

Type: object


destroy

Type: function ()


TemplateManager

Type: function (options)


_options

Type: object


_viewer

Type: TemplateManagerViewer


_env

Type: Object<string, any>


templateExists

Type: function (templateName): boolean


remove

Type: function (templateName)


add

Type: function (templateName, filePath)


addList

Type: function (templates)


get

Type: function (templateName): TemplateManagerTemplate


render

Type: function (response, templateName, vars)


SGAppsServerRequest

Type: function (request, server)


request

Type: IncomingMessage


_postDataBuffer

post data buffer cache

Type: Buffer


getMountUpdatedUrl

Type: function (url): MountUpdatedURL


urlInfo

Type: object


query

Type: object


mountPath

Type: string


body

Type: object


bodyItems

Type: Array<SGAppsServerRequestPostDataItem>


cookies

Type: SGAppsServerRequestCookie


MAX_POST_SIZE

Type: number

Examples:

// changing max post size to 4Mb
request.MAX_POST_SIZE = 4 * 1024 * 1024;
// reset max post size to global value
request.MAX_POST_SIZE = -1;

files

Type: Object<string, Array<SGAppsServerRequestFile>>


fileItems

Type: Array<SGAppsServerRequestFile>


_destroy

Array of functions to be called on response end

Type: Array<function>


params

Array of functions to be called on response end

Type: SGAppsServerRequest.RequestParams


_flags

Array of functions to be called on response end

Type: object

  • complete boolean The message.complete property will be true if a complete HTTP message has been received and successfully parsed.
  • aborted boolean The message.aborted property will be true if the request has been aborted.
  • closed boolean Indicates that the underlying connection was closed.
  • _DEBUG_MAX_HANDLER_EXECUTION_TIME number? define a bigger request timeout

_parseDeepFieldName

Automatically used procedure for parsing formData field name if option server._options._REQUEST_FORM_PARAMS_DEEP_PARSE = true. it's by default enabled but can be disabled when needed

Type: function (container, fieldName, fieldData, options)

  • container object
  • fieldName string
  • fieldData any
  • options object?
    • options.transform2ArrayOnDuplicate boolean (optional, default false)

Examples:

paramsContainer = {};
request._parseDeepFieldName(paramsContainer, 'test[arr][data]', 2);
request._parseDeepFieldName(paramsContainer, 'test[arr][]', new Date());
request._parseDeepFieldName(paramsContainer, 'test[arr][]', 2);
request._parseDeepFieldName(paramsContainer, 'test[data]', 2);
// if _debug enabled warns will be emitted
// [Warn] [Request._parseDeepFieldName] Writing Array field "test[arr][]" into a object
// [Warn] [Request._parseDeepFieldName] Overwriting field "test[data]" value
console.log(paramsContainer)
{
    "test": {
        "arr": {
            "1": "2021-02-12T21:23:01.913Z",
            "2": 2,
            "data": 2
        },
        "data": 2
    }
}
paramsContainer = {};
request._parseDeepFieldName(paramsContainer, 'test[arr][]', new Date());
request._parseDeepFieldName(paramsContainer, 'test[arr][]', 2);
request._parseDeepFieldName(paramsContainer, 'test[arr][data]', 2);
request._parseDeepFieldName(paramsContainer, 'test[data]', 2);
// if _debug enabled warns will be emitted
// [Warn] [Request._parseDeepFieldName] Converting array to object due incorrect field "test[arr][data]" name 
console.log(paramsContainer)
{
    "test": {
        "arr": {
            "0": "2021-02-12T21:34:47.359Z",
            "1": 2,
            "data": 2
        },
        "data": 2
    }
}
paramsContainer = {};
request._parseDeepFieldName(paramsContainer, 'test[arr][]', new Date());
request._parseDeepFieldName(paramsContainer, 'test[arr][]', 2);
request._parseDeepFieldName(paramsContainer, 'test[data]', 2);
console.log(paramsContainer)
{
    "test": {
        "arr": [
            "2021-02-12T21:26:43.766Z",
            2
        ],
        "data": 2
    }
}

session

Type: SGAppsServerRequestSession


postData

request's post received data

Type: Promise<Buffer>


RequestParams

Type: (Object<(string | number), string> | Array<string>)


routeMatch

Type: function (route, url, strictRouting, _cache)


SGAppsServerResponse

Type: function (response, server)


response

Type: ServerResponse


pipeFile

Type: function (filePath, callback)


send

Type: function (data, options)


sendError

Type: function (error, options)


_destroy

Array of functions to be called on response end

Type: Array<function>


redirect

if it returns false than the action was not possible

Type: function (url, options)


_flags

Array of functions to be called on response end

Type: object

  • finished boolean will be true if response.end() has been called.
  • sent boolean Is true if all data has been flushed to the underlying system, immediately before the 'finish' event is emitted.
  • closed boolean Indicates that the the response is completed, or its underlying connection was terminated prematurely (before the response completion).

pipeFileStaticCallback

Type: Function


pipeFileStatic

Type: function (filePath, fileName, callback, options)

  • filePath string
  • fileName string
  • callback SGAppsServerResponse.pipeFileStaticCallback
  • options object?
    • options.timeout number (optional, default 0)
    • options.filePath string? originap path is autoIndex was applied
    • options.autoIndex Array<string>? list of auto-index files, ex: ['index.html', 'index.htm', 'default.html']

sendStatusCode

Type: function (statusCode)


TemplateManagerRenderOptions

Type: object


TemplateManagerViewer

Type: function (options)


_facebox

Type: FaceboxTemplate


_debug

Type: boolean


_env

Type: Object<string, any>


renderCode

Type: function (code, vars, virtualFilePath, callback)


render

Type: function (response, view, vars)


TemplateManagerTemplate

Type: object


SGAppsServerEmail

Type: function (config)

  • config SGAppsServerEmail.Config optional configuration object

Example:

Example:
   var Email = require('path/to/email').Email
   var myMsg = new Email(
   { from: 'me@example.com'
   , to:   'you@example.com'
   , subject: 'Knock knock...'
   , body: "Who's there?"
   })
   myMsg.send(function(err){
     ...
   })

send

Send email

Type: function (callback)

  • callback SGAppsServerEmail.Callback

options

get message options

Type: object


encodedBody

getter generate encoded body

Type: string


msg

getter generate all email structure

Type: string


valid

check if email is valid

Type: function (callback)

  • callback SGAppsServerEmail.Callback

Config

Email : Sends email using the sendmail command.

Note: sendmail must be installed: see http://www.sendmail.org/

Type: object

  • to (Array<string> | string) Email address(es) to which this msg will be sent
  • debug boolean?
  • from string? Email address from which this msg is sent. If not set defaults to the exports.from global setting.
  • replyTo string? Email address to which replies will be sent. If not set defaults to from
  • cc (string | Array<string>)? Email address(es) who receive a copy
  • bcc (string | Array<string>)? Email address(es) who receive a blind copy
  • subject string The subject of the email
  • body string The message of the email
  • bodyType string? Content type of body. Only valid option is 'html' (for now). Defaults to text/plain.
  • altText string? If bodyType is set to 'html', this will be sent as the alternative text.
  • timeout number? Duration in milliseconds to wait before killing the process. If not set, defaults to exports.timeout global setting.
  • path string? Optional path to the sendmail executable.

from

Email address from which messages are sent. Used when from was not set on a message.

Type: function (email): string


isValidAddress

Type: function (email): boolean


timeout

Duration in milliseconds to wait before killing the process. Defaults to 3000. Used when timeout is not set on a message.

Type: function (milliseconds): number


Callback

Type: Function


SGAppsSessionManagerOptions

Type: object


SGAppsServerRequestSessionCache

Type: object


MountUpdatedURL

Type: string


FaceboxTemplate

Type: function (options)


_debug

Type: boolean


_env

Type: Object<string, any>


_cachedFiles

Type: Object<string, string>


INCLUDE_LEVEL

Type: number


render

Type: function (text, vars, env)


renderFile

Type: function (filePath, vars, callback)


renderCode

Type: function (code, vars, callback, virtualFilePath)


SGAppsServerRequestCookie

Type: function ()


get

Type: function (name, options): string


set

Type: function (name, value, options): string

  • name string
  • value string
  • options object?
    • options.secure boolean (optional, default false)
    • options.secureProxy boolean?
    • options.signed boolean?
    • options.path string (optional, default "/")
    • options.expires Date?
    • options.domain string?
    • options.httpOnly boolean (optional, default true;)
    • options.sameSite boolean (optional, default false;)
    • options.secure boolean (optional, default false;)
    • options.overwrite boolean (optional, default false;)

SGAppsServerDecoratorsLibrary

Type: function ()


SGAppsServerErrorCallBack

Type: Function


SGAppsServerErrorOnlyCallback

Type: Function


FSLibrary

Type: function ()


SGAppsServerShared

Type: function ()


SGAppsServerRequestFile

Type: object

  • fieldName string field's name
  • data object
    • data.fileName string file's name [duplicate]
    • data.encoding string file's encoding
    • data.fileStream Readable () => fileStream
    • data.fileData Buffer
    • data.fileSize number size in bytes
    • data.contentType string file's mimeType
    • data.loaded boolean indicate if file is fully loaded into fileData

SGAppsServerRequestPostDataItem

Type: object


SGAppsServerDecorator

Type: Function


SGAppsServer

HTTP Server for high performance results

Type: function (options)

  • options object?
    • options.server Server?
    • options.strictRouting boolean (optional, default true)
    • options.debug boolean (optional, default true)
    • options._DEBUG_MAX_HANDLER_EXECUTION_TIME object console shows an warn if handler is executed more than ( works in debug mode ) (optional, default 500)
    • options._DEBUG_REQUEST_HANDLERS_STATS object console shows an warn if handler is executed more than ( works in debug mode ) (optional, default false)
    • options._REQUEST_FORM_PARAMS_DEEP_PARSE boolean parse formData field names to create deep object request.body (optional, default true)
    • options.decorators Array<SGAppsServerDecorator>?

Examples:

// ================================
//   Start your ๐Ÿš€ Web-Server app
// ================================

const { SGAppsServer } = require('@sgapps.io/server');
const app = new SGAppsServer();

app.get('/', function (req, res) {
  res.send('hello world')
})

app.server().listen(8080, () => {
  app.logger.log('Server is running on port 8080');
})
// ========================================
//   Start your ๐Ÿš€ Web-Server app Extended
// ========================================

const { SGAppsServer } = require('@sgapps.io/server');
const app = new SGAppsServer();

app.get('/', function (req, res) {
  res.send('hello world')
})

app.whenReady.then(() => {
  app.SessionManager.cookie = 'ssid';
  app.SessionManager.SESSION_LIFE = 120; // seconds

  app.server().listen(8080, () => {
    app.logger.log('Server is running on port 8080');
  })
}, app.logger.error);

CookiesManager

Type: object

  • COOKIES_KEY string
  • _enabled boolean? if is changed to false server will not decorate requests with cookie manager
  • handle function (SGAppsServerRequest, SGAppsServerResponse): object

_server

Type: Server


_decorators

Type: Array<SGAppsServerDecorator>


TemplateManager

Type: TemplateManager


_options

Type: SGAppsServerOptions


STATUS_CODES

Type: Object<number, string>


shared

Type: SGAppsServerShared


logger

Type: LoggerBuilder


Email

Type: function (config): SGAppsServerEmail

  • config SGAppsServerEmail.Config

SessionManager

Type: SGAppsSessionManager


mountPath

Type: string


_fs

Type: object


_path

Type: object


EXTENSIONS

Type: ResourcesExtensions


_requestListeners

Type: Object<string, SGAppsServerDictionary>


MAX_POST_SIZE

default value is 16 Kb ยป 16 * 1024

Type: number


whenReady

Type: Promise<SGAppsServer>


handleRequest

Type: function (request, response, callback)


handleErrorRequest

Type: function (request, response, err)


handleStaticRequest

Type: function (request, response, path, callback, options)


handle

Type: function (request, response, callback)


server

Type: function (): Server


use

Type: `fu