Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add custom stringify and parse props functions #68

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
49 changes: 49 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,55 @@ function createPage(html, scriptTag) {

## API

### setCustomCreateScriptTagMethod

You can use custom `createScriptTag(json)` function to escape html symbols json for example.
By default, AsyncProps use:

```js
function createScriptTag(json){
return `<script>__ASYNC_PROPS__ = ${json}</script>`
}
```

You can specify your own function:

```js
import { setCreateScriptTagMethod } from 'async-props'

setCreateScriptTagMethod(function(json){
return `<script>__ASYNC_PROPS__ = decodeURI(${encodeURI(json)})</script>`
})
```

As you see, you function should return `'<script>__ASYNC_PROPS__ =' + some_json_with_optional_wrapping + '</script>'`


### setCustomStringifyPropsMethod

You can use custom `stringifyProp(propsArray)` function to minify json on production for example.
By default, AsyncProps use:

```js
function (propsArray){
return JSON.stringify(propsArray, null, 2)
}
```

You can specify your own function:

```js
import { setStringifyPropsMethod } from 'async-props'

setStringifyPropsMethod(function(propsArray){
return JSON.stringify(propsArray)
})
```

As you see, you function should String, that you can parse on client.

---------

Please refer to the example, as it exercises the entire API. Docs will
come eventually :)

35 changes: 27 additions & 8 deletions modules/AsyncProps.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function filterAndFlattenComponents(components) {
return flattened
}

function loadAsyncProps({ components, params, loadContext }, cb) {
function loadAsyncProps({ components, params, location, loadContext }, cb) {
let componentsArray = []
let propsArray = []
let needToLoadCounter = components.length
Expand All @@ -44,7 +44,7 @@ function loadAsyncProps({ components, params, loadContext }, cb) {
maybeFinish()
} else {
components.forEach((Component, index) => {
Component.loadProps({ params, loadContext }, (error, props) => {
Component.loadProps({ params, location, loadContext }, (error, props) => {
const isDeferredCallback = hasCalledBack[index]
if (isDeferredCallback && needToLoadCounter === 0) {
cb(error, {
Expand Down Expand Up @@ -93,18 +93,35 @@ function createElement(Component, props) {
return <Component {...props}/>
}

export function loadPropsOnServer({ components, params }, loadContext, cb) {
function stringifyProps(propsArray){
return JSON.stringify(propsArray, null, 2)
}

export function setStringifyPropsMethod(newStringifyPropsMethod){
stringifyProps = newStringifyPropsMethod;
}

function createScriptTag(json){
return `<script>__ASYNC_PROPS__ = ${json}</script>`
}

export function setCreateScriptTagMethod(newCreateScriptTagMethod){
createScriptTag = newCreateScriptTagMethod;
}

export function loadPropsOnServer({ components, params, location }, loadContext, cb) {
loadAsyncProps({
components: filterAndFlattenComponents(components),
params,
location,
loadContext
}, (err, propsAndComponents) => {
if (err) {
cb(err)
}
else {
const json = JSON.stringify(propsAndComponents.propsArray, null, 2)
const scriptString = `<script>__ASYNC_PROPS__ = ${json}</script>`
const json = stringifyProps(propsAndComponents.propsArray)
const scriptString = createScriptTag(json)
cb(null, propsAndComponents, scriptString)
}
})
Expand Down Expand Up @@ -222,14 +239,15 @@ const AsyncProps = React.createClass({
if (nextProps.location === this.props.location)
return

const { enterRoutes } = computeChangedRoutes(
const { enterRoutes, changeRoutes } = computeChangedRoutes(
{ routes: this.props.routes, params: this.props.params },
{ routes: nextProps.routes, params: nextProps.params }
)

const indexDiff = nextProps.components.length - enterRoutes.length
const checkRoutes = enterRoutes.concat(changeRoutes.filter((route)=>(route.component && route.component.isQueryDepend)))
const indexDiff = nextProps.components.length - checkRoutes.length
const components = []
for (let i = 0, l = enterRoutes.length; i < l; i++)
for (let i = 0, l = checkRoutes.length; i < l; i++)
components.push(nextProps.components[indexDiff + i])

this.loadAsyncProps(
Expand Down Expand Up @@ -261,6 +279,7 @@ const AsyncProps = React.createClass({
loadAsyncProps({
components: filterAndFlattenComponents(components),
params,
location,
loadContext
}, this.handleError((err, propsAndComponents) => {
const reloading = options && options.reload
Expand Down
40 changes: 39 additions & 1 deletion modules/__tests__/AsyncProps-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import expect, { spyOn, restoreSpies } from 'expect'
import createHistory from 'react-router/lib/createMemoryHistory'
import { render } from 'react-dom'
import { Router, Route, match } from 'react-router'
import AsyncProps, { loadPropsOnServer } from '../AsyncProps'
import AsyncProps, { loadPropsOnServer, setCreateScriptTagMethod, setStringifyPropsMethod } from '../AsyncProps'

const createRunner = (routes, extraProps) => {
return ({ startPath, steps }) => {
Expand Down Expand Up @@ -146,6 +146,44 @@ describe('server rendering', () => {
})
})
})

describe('customise script tag by user', function(){
afterEach(function(){
setStringifyPropsMethod(function(json){
return JSON.stringify(json, null, 2) //default
});
setCreateScriptTagMethod(function (json){
return `<script>__ASYNC_PROPS__ = ${json}</script>`
})
});
it('allow to replace default JSON#stringify() by user stringify method', () => {
match({ routes, location: '/' }, (err, redirect, renderProps) => {
function someStringifyMethod(props){
return JSON.stringify(props);
}
setStringifyPropsMethod(someStringifyMethod);
loadPropsOnServer(renderProps, {}, (err, data, scriptString) => {
expect(scriptString).toEqual(
`<script>__ASYNC_PROPS__ = ${JSON.stringify([ DATA ])}</script>`
)
})
})
})

it('allow to change script tag with user createScriptTagMethod', () => {
match({ routes, location: '/' }, (err, redirect, renderProps) => {
function createSomeTag(json){
return `<script>__ASYNC_PROPS__ = decodeURIComponent(${json})</script>`
}
setCreateScriptTagMethod(createSomeTag);
loadPropsOnServer(renderProps, {}, (err, data, scriptString) => {
expect(scriptString).toEqual(
`<script>__ASYNC_PROPS__ = decodeURIComponent(${JSON.stringify([ DATA ], null, 2)})</script>`
)
})
})
})
})
})

// These tests are probably overkill for the implementation, could
Expand Down
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
{
"name": "async-props",
"version": "0.3.2",
"name": "async-props-nfs",
"version": "0.4.4",
"description": "Co-located component data fetching for React Router",
"main": "lib/AsyncProps",
"repository": {
"type": "git",
"url": "https://github.com/rackt/async-props.git"
"url": "https://github.com/NumminorihSF/async-props-nfs.git"
},
"bugs": "https://github.com/rackt/async-props/issues",
"bugs": "https://github.com/NumminorihSF/async-props-nfs/issues",
"scripts": {
"build": "babel ./modules -d lib --ignore '__tests__'",
"build-umd": "NODE_ENV=production webpack modules/AsyncProps.js umd/AsyncProps.js",
Expand All @@ -18,7 +18,8 @@
"postinstall": "node ./npm-scripts/postinstall.js"
},
"authors": [
"Ryan Florence"
"Ryan Florence",
"Konstantin Petryaev"
],
"license": "MIT",
"peerDependencies": {
Expand Down