STAXIS

staxis js platform -> gitlab project
staxis on gitlab gitlab project 🏷️ V-0.X-Beta
We’re actively updating this manual. Content and layout may change as we refine it.

httpRestParser

Official sources are open to Staxis GitLab group members: how to join and view the code.
Repository: httpRestParser development
Versions: tags and releases


Description

httpRestParser is an I/O helper library: receiver collects request data, while emitter sends buffered, streamed, or progressive responses. It helps keep route handlers uniform when receiving body and query parameters or uploaded files. Its manifest.label is httpRestParser and its manifest.typology is library. It belongs to the HTTP family but does not register middleware or open routes by itself.


Read before flight

  • We suggest choosing one reader for each request body. Call receiver before another middleware consumes the raw stream, especially for multipart uploads.

  • We suggest setting request limits for your expected traffic and available memory. Raw bodies and multipart files are buffered in memory; the multipart limit covers the complete request, not each file or the combined traffic of concurrent requests.

  • We suggest validating parsed values and uploaded contents in the consuming layer. Treat filenames and content types as client metadata, select storage and streaming paths in application code, and check whether a response has already ended before replying.


Requirements and Installation

No extra npm dependency or required pack dependency is declared. Install through the Manager:

                manager -> install -> httpRestParser
            

Place the library before layers that consume it in the stack. The examples below use the native serverApp application, already obtained by the consuming layer through its authorised access. Declare the packs used by that layer in its manifest requirements. The library itself does not need serverApp to parse compatible request and response objects.


Files Map

File Purpose
manifest.json Declares the library identity and main entry point
configs.js Supplies the multipart limit and Guardian filesystem permission
main.js Implements receiver and the buffer, stream, and monitor emitters
README.md Practical usage reference for the pack
.fomap Lists the installed pack files

Configuration

In the project's config.js, the multipart limit belongs to config.serveropt.httpMultipartLimit. The supplied default is 10 MiB. Filesystem permission belongs to config.engineopt.guard.allowedFileAccess and is needed only for emitter.stream. The pack supplies roots=true; this example narrows access to the project temporary directory used below. Merge these branches into the exported config object, preserving other pack rules.

                // config.js -> config (merge into the exported object)
                engineopt: {
                    guard: {
                        allowedFileAccess: [
                            {
                                pack: 'httpRestParser', // Library pack's manifest.label
                                roots: ['./system-temp', './system-temp/*']
                            }
                        ]
                    }
                },
                serveropt: {
                    httpMultipartLimit: 10 * 1024 * 1024
                }
            

For raw non-multipart bodies, receiver uses a positive config.serveropt.httpShield.rawlimit, or 10 MiB when that value is unavailable. Multipart uses httpMultipartLimit first, then the same fallback. If a framework has already prepared a non-multipart body, receiver reuses it instead of collecting and counting the raw bytes again. Set the framework's body limit at its own parsing stage too.


Load the Library

                const parser = libraries.require('httpRestParser') // Library pack's manifest.label
                
                if (!parser) throw new Error('httpRestParser is unavailable')
            

Use libraries.require for this library; no Vault token is passed to that call. The helpers accept native Node objects and unwrap common Fastify raw and Koa req/res containers. Framework body parsing and response ownership still belong to the chosen application adapter. The following route examples use native req and res.


Receive Body and Query Data

receiver(req, res, callback) supplies a result with errors, message, and payload. The client can put values in the body, the query string, or both. Register a route like this:

                serverApp.using('example-route', (req, res, next) => {
                
                    if (req.url?.split('?')[0] !== '/api/test') return next()
                
                    return parser.receiver(req, res, result => {
                
                        if (res.writableEnded || res.destroyed) return
                
                        return parser.emitter.buffer(req, res, result)
                
                    })
                
                })
            

These requests produce the same payload. Adjust the address to your listener:

                POST /api/test
                Content-Type: application/json
                Body: { "name": "Ada", "role": "admin" }
                
                GET /api/test?name=Ada&role=admin
                
                POST /api/test?role=admin
                Content-Type: application/json
                Body: { "name": "Ada" }
            
                {
                    "errors": false,
                    "message": "request data parsed",
                    "payload": {
                        "name": "Ada",
                        "role": "admin"
                    }
                }
            

Repeated query parameters are preserved as arrays: /api/test?tag=node&tag=staxis produces payload.tag equal to ['node', 'staxis']. When an object body and the query contain the same key, the query value takes precedence. Validate this combined input before using it as application data.

Raw application/json and application/*+json bodies are decoded as JSON; application/x-www-form-urlencoded bodies are decoded as form values, preserving repeated names as arrays. Other raw bodies become UTF-8 text. A text or scalar body is returned directly when there is no query, or under payload.body alongside query values when there is one. An empty request produces an empty object.

Malformed JSON or multipart data produces a 400 response. An oversized raw body produces 413. The callback still receives an error result after the library has completed the failed HTTP response; the writableEnded/destroyed check above avoids sending another response. Keep domain validation separate from these transport errors and return your own HTTP status when needed.


Receive a Multipart Payload

For multipart/form-data, payload contains fields and files. Query values are included in fields; repeated text fields are accumulated as arrays. files is always an array, even for a single upload. Each file keeps its original binary bytes in a Buffer. The parser does not save uploads to disk.

                serverApp.using('upload-route', (req, res, next) => {
                
                    if (req.url?.split('?')[0] !== '/api/upload') return next()
                
                    return parser.receiver(req, res, result => {
                
                        if (res.writableEnded || res.destroyed) return
                
                        if (result.errors || !Array.isArray(result.payload?.files)) {
                            res.statusCode = 400
                            return res.end('Expected a multipart upload')
                        }
                
                        const { fields, files } = result.payload
                
                        return parser.emitter.buffer(req, res, {
                            errors: false,
                            message: files.length + ' files received',
                            payload: fields
                        })
                
                    })
                
                })
            
Property of each file Meaning
field Form field name, such as document
filename Client-provided filename, such as invoice.pdf
contentType Part content type, or application/octet-stream when absent
size Number of file-content bytes
buffer Binary Buffer containing the file contents

Choose how many files and which fields your application accepts. A single file per request can make validation and retries simpler, while multiple files remain supported. Neither filename nor contentType proves the actual file format, and filename must not become an unchecked storage path.


Store an Uploaded File with File Manager

The consuming layer obtains filemanager separately. Its manifest label must be permitted by filemanager, and its config.engineopt.filemanager.access profile must allow writing the selected destination. Prepare the destination directory as described in the File Manager manual. The path below is relative to File Manager's managed temporary tree, so incoming/document.bin is stored beneath system-temp/incoming.

                const token = engine.vault.requireAccess(
                    'someOtherLayer', // Requesting layer's manifest.label
                    'filemanager'     // Target pack's manifest.label
                )
                
                const filemanager = layers.require(
                    'filemanager', // Target layer's manifest.typology: its runtime slot
                    token,
                    false
                )?.assets
                
                if (!filemanager) throw new Error('filemanager is unavailable')
            

Inside the upload route, replace its receiver callback with the following. The application selects a fixed destination here; in a real workflow choose an authorised, collision-safe name for each stored file.

                return parser.receiver(req, res, async result => {
                
                    if (res.writableEnded || res.destroyed) return
                
                    const uploaded = result.payload?.files?.[0]
                
                    if (result.errors || !uploaded) {
                        res.statusCode = 400
                        return res.end('File not received')
                    }
                
                    const stored = await filemanager.write(token, uploaded.buffer, 'incoming/document.bin')
                
                    if (res.writableEnded || res.destroyed) return
                
                    return parser.emitter.buffer(req, res, stored)
                
                })
            

Send a Standard Response

emitter.buffer sends a complete response already available in memory. Objects are serialized with JSON.stringify; strings are sent unchanged. With unsent headers, it sets status 200, text/plain; charset=utf-8, and the UTF-8 byte length. JSON serialization does not change that default content type. Use explicit response handling when your API needs another status or media type.

                parser.emitter.buffer(req, res, {
                    ok: true,
                    result: ['first', 'second']
                })
            

Stream a File

emitter.stream reads a selected file through engine.fileaccess and sends application/octet-stream, Content-Length, and Cache-Control: no-store. It does not create an archive or apply File Manager's access profiles. Use trusted application logic to choose the path and keep the library's Guardian rule appropriate.

                serverApp.using('report-route', (req, res, next) => {
                
                    if (req.url?.split('?')[0] !== '/api/report') return next()
                
                    return parser.emitter.stream(req, res, '../../system-temp/report.bin')
                
                })
            

Create report.bin before requesting this route. With the standard installation in system-lrpcks/httpRestParser, the relative path above reaches the project's system-temp directory. The path is resolved from the library's main.js location, not the consuming route's file. Absolute paths and forbidden schemes are rejected by the Core filesystem gate.

A missing file produces 404; inspection or read failures produce 500 while headers can still be sent. Once streaming has begun, an error cannot replace the already-sent HTTP status. The helper starts streaming and returns immediately; it does not return a promise for transfer completion.


Send Progressive Updates

monitor opens an application/x-ndjson response for incremental progress. Start once, await successive writes, then finish with close or error. Each write waits for backpressure and stops waiting if the response closes or emits an error. Your operation remains responsible for cancellation when a client disconnects.

                serverApp.using('progress-route', async (req, res, next) => {
                
                    if (req.url?.split('?')[0] !== '/api/progress') return next()
                
                    parser.emitter.monitor.start(req, res)
                
                    await parser.emitter.monitor.write(res, {
                        phase: 'prepare',
                        progress: 10
                    })
                
                    await parser.emitter.monitor.write(res, {
                        phase: 'process',
                        progress: 70
                    })
                
                    parser.emitter.monitor.close(req, res, {
                        ok: true,
                        progress: 100
                    })
                
                })
            

Place the real work between the relevant updates. To see output as it arrives:

                curl -N http://127.0.0.1:3000/api/progress
            

To finish with an application error, use error instead of close:

                parser.emitter.monitor.error(req, res, {
                    ok: false,
                    message: 'Processing failed'
                }, 500)
            

start flushes status 200 when supported. After headers are sent, the 500 argument cannot change the HTTP status: the final payload communicates the failure. We suggest using objects for updates and making clients inspect that final result rather than relying only on HTTP status.

Method Arguments
receiver req, res, callback
emitter.buffer req, res, data
emitter.stream req, res, relativeFilePath
emitter.monitor.start req, res
emitter.monitor.write res, data; returns a promise
emitter.monitor.close req, res, data; defaults to { ok: true }
emitter.monitor.error req, res, data, status; defaults to { ok: false } and 400

Documentation

This page is the HTML adaptation of the pack's README.md, with practical clarifications checked against the implementation. Complete Staxis onboarding to request GitLab access to the official sources.