Skip to content

Commit

Permalink
demo: Support some pagination.
Browse files Browse the repository at this point in the history
  • Loading branch information
Justin Harris committed Dec 16, 2019
1 parent b753fc5 commit ef09d6d
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 44 deletions.
72 changes: 50 additions & 22 deletions demo/client/src/containers/modelList.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Button from '@material-ui/core/Button';
import Container from '@material-ui/core/Container';
import Divider from '@material-ui/core/Divider';
import List from '@material-ui/core/List';
Expand All @@ -18,7 +19,11 @@ import { DataStoreFactory } from '../storage/data-store-factory';
const styles = theme => ({
link: {
color: theme.palette.primary.main,
}
},
button: {
marginTop: 20,
marginBottom: 20,
},
});

class ModelList extends React.Component {
Expand All @@ -31,32 +36,17 @@ class ModelList extends React.Component {
this.state = {
models: [],
}

this.nextModels = this.nextModels.bind(this)
}

componentDidMount = async () => {
const web3 = await getWeb3()
const networkType = await web3.eth.net.getNetworkType()
const validator = new OnlineSafetyValidator()
// TODO Change to 10 before merging.
const limit = 1
this.networkType = await web3.eth.net.getNetworkType()
this.validator = new OnlineSafetyValidator()
checkStorages(this.storages).then(permittedStorageTypes => {
permittedStorageTypes.filter(storageType => storageType !== undefined)
.forEach(storageType => {
const afterId = this.storageAfterAddress[storageType]
return this.storages[storageType].getModels(afterId, limit).then(newModels => {
newModels.forEach(model => {
model.restrictContent = !validator.isPermitted(networkType, model.address)
})
if (newModels.length > 0) {
this.storageAfterAddress[storageType] = newModels[newModels.length - 1].address
}
this.setState(prevState => ({ models: prevState.models.concat(newModels) }))
}).catch(err => {
this.notify(`Could not get ${storageType} models`, { variant: 'error' })
console.error(`Could not get ${storageType} models.`)
console.error(err)
})
})
permittedStorageTypes = permittedStorageTypes.filter(storageType => storageType !== undefined)
this.setState({ permittedStorageTypes }, this.updateModels)
})
}

Expand All @@ -68,6 +58,32 @@ class ModelList extends React.Component {
return this.props.closeSnackbar(...args);
}

nextModels() {
this.setState({ models: [] }, this.updateModels)
}

updateModels() {
// TODO Also get valid contracts that the account has already interacted with.
// TODO Change to 10 before merging.
const limit = 1
this.state.permittedStorageTypes.forEach(storageType => {
const afterId = this.storageAfterAddress[storageType]
return this.storages[storageType].getModels(afterId, limit).then(newModels => {
newModels.forEach(model => {
model.restrictContent = !this.validator.isPermitted(this.networkType, model.address)
})
if (newModels.length > 0) {
this.storageAfterAddress[storageType] = newModels[newModels.length - 1].address
}
this.setState(prevState => ({ models: prevState.models.concat(newModels) }))
}).catch(err => {
this.notify(`Could not get ${storageType} models`, { variant: 'error' })
console.error(`Could not get ${storageType} models.`)
console.error(err)
})
})
}

render() {
let listItems = [];
if (this.state.models) {
Expand Down Expand Up @@ -98,6 +114,12 @@ class ModelList extends React.Component {

return (
<Container>
{/* TODO Only show if there are more models. */}
<Button className={this.props.classes.button} variant="outlined" color="primary"
onClick={this.nextModels}
>
Next
</Button>
<Paper>
<List component="nav" className={this.props.classes.list}>
{listItems ? listItems :
Expand All @@ -107,6 +129,12 @@ class ModelList extends React.Component {
}
</List>
</Paper>
{/* TODO Only show if there are more models. */}
<Button className={this.props.classes.button} variant="outlined" color="primary"
onClick={this.nextModels}
>
Next
</Button>
</Container>
);
}
Expand Down
3 changes: 2 additions & 1 deletion demo/client/src/storage/local-data-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ export class LocalDataStore implements DataStore {
const models: ModelInformation[] = []
let range
if (afterAddress !== null && afterAddress !== undefined) {
range = IDBKeyRange.lowerBound(afterAddress)
const open = true
range = IDBKeyRange.lowerBound(afterAddress, open)
} else {
range = null
}
Expand Down
10 changes: 9 additions & 1 deletion demo/client/src/storage/service-data-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,15 @@ export class ServiceDataStore implements DataStore {
}

getModels(afterAddress?: string, limit?: number): Promise<ModelInformation[]> {
return axios.get(`${this.url}/api/models?afterAddress=${afterAddress}&limit=${limit}`).then(response => {
const params = []
if (afterAddress != null) {
params.push(`afterAddress=${afterAddress}`)
}
if (limit != null) {
params.push(`limit=${limit}`)
}
const url = `${this.url}/api/models?${params.join('&')}`
return axios.get(url).then(response => {
return response.data.models.map((model: any) => new ModelInformation(model))
})
}
Expand Down
40 changes: 20 additions & 20 deletions demo/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,33 +41,33 @@ initSqlJs().then(SQL => {
fs.writeFileSync(dbPath, Buffer.from(db.export()));
}

function marshalResults(res) {
if (!res[0]) {
return [];
}

return res[0].values.map(v => ({
'id': v[0],
'name': v[1],
'address': v[2],
'description': v[3],
'modelType': v[4],
'encoder': v[5],
'accuracy': v[6]
}));
}

// Health
app.get('/api/health', (req, res) => {
res.send({ healthy: true });
})

// Get all models.
app.get('/api/models', (req, res) => {
const { afterAddress, limit } = req.query;
// TODO Use params.
const results = db.exec("SELECT * FROM model");
const models = marshalResults(results);
const { afterAddress, limit } = req.query
const getStmt = db.prepare('SELECT * FROM model WHERE address > $afterAddress LIMIT $limit;',
{
$afterAddress: afterAddress || '',
$limit: limit || 10
});
const models = []
while (getStmt.step()) {
const model = getStmt.get()
models.push({
'id': model[0],
'name': model[1],
'address': model[2],
'description': model[3],
'modelType': model[4],
'encoder': model[5],
'accuracy': model[6]
});
}
getStmt.free();
res.send({ models });
});

Expand Down

0 comments on commit ef09d6d

Please sign in to comment.