Skip to content

Commit

Permalink
small cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
sc0ttj authored and sc0ttj committed Nov 2, 2020
1 parent a7b21f0 commit 8e79d68
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 36 deletions.
26 changes: 17 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@

router({

'/home': (params) => { ... },
'/home': (params) => { ... },

'/profile/:id': (params) => { ... },

Expand All @@ -47,6 +47,14 @@

```

The supported route pattern types are:

* static (`/users`)
* named parameters (`/users/:id`)
* nested parameters (`/users/:id/books/:title`)
* optional parameters (`/posts(/:slug)`)
* any match / wildcards (`/users/*`)

## Installation

### In browsers:
Expand All @@ -73,7 +81,7 @@ router = require('@scottjarvis/router');

```

## Usage in browsers: as a client-side router
## Usage in browsers: as a client-side router

For routing frontend JS stuff like "single page applications", you'll need to trigger the router when the URL changes, or a link is clicked.

Expand Down Expand Up @@ -128,16 +136,16 @@ http.createServer((req, res) => {
{
"/home": params => {
console.log("home!", params)
// set header status to "200",
// set header status to "200",
// set content-type to "text/html",
// set content, end response
res.send("<p>some string</p>")
},
"/user/:userId": params => {
console.log("serving JSON!", params)
// set header to "200" manually
// set header to "200" manually
// set content-type to "application/json",
// set content (prettified JSON)
// set content (prettified JSON)
// end response
res.status(200)
res.send(params)
Expand All @@ -164,8 +172,8 @@ There is a `res.send()` method, which makes life easier for you:
* `text/html` - if given a string
* `application/json` - if given an object, array or JSON
* `application/octet-stream` - if given a Buffer
- pretty prints JSON output
- calls `res.end()` for you
- pretty prints JSON output
- calls `res.end()` for you

The `res.json()` method is similar to above, but sends the Content-Type `application/json`.

Expand Down Expand Up @@ -340,7 +348,7 @@ Rebuild the bundles in `dist/` using this command: `npm run build`
### Alternative routers
- [director](https://github.com/flatiron/director) - a fairly small, isomorphic URL router for JavaScript
- [hasher](https://github.com/narirou/hasher) - Tiny hashchange router inspired by express.js & page.js
- [hasher](https://github.com/narirou/hasher) - Tiny hashchange router inspired by express.js & page.js
- [routie](https://github.com/jgallen23/routie) - a tiny javascript hash router
- [trouter](https://github.com/lukeed/trouter/) - a fast, small-but-mighty, familiar router
- [RouterRouter](https://github.com/jgarber623/RouterRouter) - a tiny JS router, extracted from Backbone's Router
Expand Down Expand Up @@ -370,7 +378,7 @@ This should improve compatibility with other express.js middleware that is loade
### Basic auth middleware
See
See
- https://github.com/jshttp/basic-auth
- https://github.com/arkerone/api-key-auth
Expand Down
14 changes: 10 additions & 4 deletions examples/http-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ http
// * router added req.params to the params received here
// * router provides res.send() and res.status()
// * res.status() : set the header status (optional)
res.status(200)
// * res.send() :
// - sets header status to 200 (if res.status not used)
// - sets appropriate content type:
Expand All @@ -50,17 +51,15 @@ http
// - sanitises the content:
// * auto pretty prints JSON output
// - ends the response
res.status(200)
res.send(params)
},
// any other route
"*": params => {
res.send("<h1>API Docs:</h1>")
res.send("<h1>API Docs:</h1><p>Do /home or /user/1, /user/2, etc... That's it.</p>")
}
},
// for servers, you must pass in 'res' and 'req' after the routes object
req,
res
req, res
)
})
.listen("8181")
Expand All @@ -84,6 +83,9 @@ var getRequestTime = function(req, res, next) {
router.use(getRequestTime)

//
// -------------- Configurable middleware examples --------------------
//

// OPTIONAL HTTP Router usage: Configurable middleware
//
// wrap your middleware in a function that takes
Expand All @@ -102,6 +104,10 @@ function configurableMiddleware(opts) {
// pass the configurable middleware function to router.use(), with your options
router.use(configurableMiddleware({ foo: "bar" }))

//
// -------------- More middleware examples --------------------
//

// you can also pass an array of middlewares
router.use([getRequestTime, configurableMiddleware({ foo: "bar" })])

Expand Down
49 changes: 26 additions & 23 deletions src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ function router(routes, req, res, cb) {
false
)

// get url path from URL, without the domain if possible
var getUrlPath = function() {
if (!!window.location.host) {
urlPath = window.location.href.toString().split(window.location.host)[1]
Expand All @@ -62,28 +63,7 @@ function router(routes, req, res, cb) {
return urlPath;
}

// get the urlPath (depends on env we're running in)
if (isBrowser) {
// Get current URL path - everything after the domain name
urlPath = getUrlPath();
} else if (isNodeServer) {
// get the URL requested in the HTTP request
if (typeof req != "undefined" && req.url) urlPath = "#" + req.url
} else if (isNode && !isNodeServer) {
// get the URL from the first argument passed to this script
if (process && process.argv) urlPath = "#" + process.argv[2]
} else if (isLambda) {
// grab the lambda params (event, context, callback) from the router params
var event = req
var context = res
var callback = cb
// get the URL requested in the HTTP request
if (typeof event !== "undefined" && event.path) urlPath = "#" + event.path
}

// getting the path, without tthe leading "#" char
var routeFromUrl = urlPath.split("#")[1]

// take query string, return it as an object
var objFromQs = function (str) {
return str.split('&')
.map((value) => value.split('=', 2))
Expand Down Expand Up @@ -309,9 +289,32 @@ function router(routes, req, res, cb) {
wrappedMiddleware.push(wrappedFn)
})
}

var wrappedMiddleware = []
wrapMiddleware()

// get the urlPath (depends on env we're running in)
if (isBrowser) {
// Get current URL path - everything after the domain name
urlPath = getUrlPath();
} else if (isNodeServer) {
// get the URL requested in the HTTP request
if (typeof req != "undefined" && req.url) urlPath = "#" + req.url
} else if (isNode && !isNodeServer) {
// get the URL from the first argument passed to this script
if (process && process.argv) urlPath = "#" + process.argv[2]
} else if (isLambda) {
// grab the lambda params (event, context, callback) from the router params
var event = req
var context = res
var callback = cb
// get the URL requested in the HTTP request
if (typeof event !== "undefined" && event.path) urlPath = "#" + event.path
}

// getting the path, without tthe leading "#" char
var routeFromUrl = urlPath.split("#")[1]

// get routePattern from URL
var routePattern = router.getRoutePatternFromUrlPath(urlPath)

Expand Down Expand Up @@ -496,7 +499,7 @@ function router(routes, req, res, cb) {
// to implement our authorization.

// now call the first middleware. It will call 2nd one, etc
wrappedMiddleware[0]
wrappedMiddleware[0]()

// parse the body into a usable JS object
var bodyParams = {}
Expand Down

0 comments on commit 8e79d68

Please sign in to comment.