Giter Site home page Giter Site logo

stitchng / adonis-extensions Goto Github PK

View Code? Open in Web Editor NEW
4.0 2.0 0.0 712 KB

An addon/plugin package to provide core extensions for AdonisJS 4.0+

License: MIT License

JavaScript 100.00%
core-extension adonisjs-framework extend-request extend-response extend-view extend-route

adonis-extensions's Introduction

adonis-extensions

An addon/plugin package to provide core extensions for AdonisJS 4.x+

NPM Version Build Status Coveralls

Getting Started

Please ensure you read the instructions.md file to get the best information about how to setup this package for optimal use

  $ adonis install adonisjs-extensions

Usage

Using custom context routines for .edge files in resources/views

<!-- The http origin of the wep app is available as a global view variable in the .edge view file(s) -->
 <link rel="canonical" href="{{ origin }}/user/me">

 <div class="wrapper">
 {{ toButton('Send', { className:'btn-primary btn', id:'submit' }) }} <!-- <button  id="submit" class="btn-primary btn">Send</button> -->

 {{ toImage('images/category-one.jpg', { alt: 'ahoy everyone' }) }} 
 <!-- <img src="http:127.0.0.1:3333/public/images/category-one.jpg" alt="ahoy everyone"> -->

 {{ toBigTextBox({ name:'tagline', className:'form-box' }, 'Just Say Hi!') }}
 <!-- <textarea class="form-box" name="tagline">Just Say Hi!</textarea> -->

 {{ toTextBox({ type:'text', name:'description', placeholder:'Enter Text...', className:'border form-input' }, 'Always opened') }} 
 <!-- <input class="border form-input" name="description" type="text" placeholder="Enter Text..." value="Always opened"> -->

 {{ toComboBox({ name:'greetings' }, [{text:'Hello',value:'hello'}, {text:'World',value:'world',selected:true}]) }} 
 <!-- <select name="greeting"><option value="hello">Hello</option>
<option value="world" selected="selected">World</option></select> -->

 {{ toFrame('https://www.example.com', { scrolling:'no' }) }}  
 <!-- <iframe src="https://www.example.com" scrolling="no"></iframe> -->

 {{ favIcon('images/favicon.ico') }} 
 <!-- <link rel="shortcut icon" href="http://127.0.0.1:3333/public/images.favicon.ico" type="image/x-icon">  -->
 </div>

 <footer>
    <!-- The full year can be included for using the global view variable too -->
    <p> Copyright &copy; {{ full_year }}. All Rights Reserved </p>
 </footer>

Using a paramsMatch() custom method in routes for start/routes.js (to sanitize route parameters at the start of the request cycle). A Cache headers middleware is available for use to set caching prefereces for assets

'use strict'

/** @type {typeof import('@adonisjs/framework/src/Route/Manager')} */
const Route = use('Route')

 Route.get('/insights/stats/:category', 'AnalyticsController.getInsights')
    .as('analytics.stats')
    .paramsMatch({category:/^([a-f0-9]{19})$/})
    .middleware(['cache.headers:private,must-revalidate,max-age=6800'])

Use custom methods on the request and response object(s) of the HttpContext object in middlewares/controllers files

'use strict'

class RouteNameAndRequestChecker {

    async handle({ request, response }, next){
	    let isAjax = request.ajax()
      // get the origin of the adonisjs server
      let origin = request.origin()
      // get the request fingerprint of the adonisjs server (unique per request)
      let fingerprint = request.fingerprint()

      if (!origin.contains('.oaksearch.com.ng')
            && request.currentRoute().isNamed('analytics.*')) { // 'analytics.stats' route will pass here
 
        // set multiple headers safely in one go.
        response.setHeaders({
          'X-App-Recall-Count': '1',
          'X-Request-Fingerprint': fingerprint
        })

        const delay = function callback (time) {
          return new Promise((resolve) => {
            return setTimeout(resolve, time)
          })
        }

        // Transform the response so that it is streamed (NodeJS streams)
        /** @HINT: 
                
          setup HTTP (NodeJS streamed) response as chunked and HTTP "Content-Type: multipart/x-mixed-replace" 
          using utf-8 encoding 
        */
        response.transform('utf8', { chunked: true, multipart: true })

        if (isAjax) {
          for (let count = 0; count < 5; count++) {
            if (count === 4) {
              // EOF sentinel to signal to the NodeJS stream
              // to close and trigger and end to the response
              // write-stream
              response.sendToStream(null)
              break;
            }

            // delay with a promise using `setTimeout()`
            await delay(count * 1000)

            // send data to the NodeJS stream (read-stream)
            // first argument is the data you wish to send to the HTTP client
            // second argument is the content-type of the multipart section for "Content-Type: multipart/x-mixed-replace"
            response.sendToStream({ time: Date.now() }, 'application/json; charset=utf-8')
          }
          return;
        }
      }

      await next();
    }
}

module.exports = RouteNameAndRequestChecker

License

MIT

Running Tests

    npm i
    npm run lint
    
    npm run test

Credits

Contributing

See the CONTRIBUTING.md file for info

Support

Coolcodes is a non-profit software foundation (collective) created by Oparand - parent company of StitchNG, Synergixe based in Abuja, Nigeria. You'll find an overview of all our work and supported open source projects on our Facebook Page.

Follow us on facebook if you can to get the latest open source software/freeware news and infomation.

Does your business depend on our open projects? Reach out and support us on Patreon. All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.

adonis-extensions's People

Contributors

dependabot[bot] avatar devamaz avatar isocroft avatar stitchng avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

adonis-extensions's Issues

optional parameters fail `paramsMatch()` validation always

Package version

v0.0.7

Node.js and npm version

NodeJS - v10.15.1
NPM - v6.4.1

Sample Code (to reproduce the issue)

Route.get('/users/:user_id?', function({ params, view }){
    return view.render('index', );
}).paramsMatch({user_id:/^([\d]{0,})$/})

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.