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

feat: support i18n and rules config #7

Open
wants to merge 20 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,16 +65,20 @@ exports.index = function* () {

### Extend Rules

- app.js
- config.default.js

```js
app.validator.addRule('jsonString', (rule, value) => {
try {
JSON.parse(value);
} catch (err) {
return 'must be json string';
exports.validate = {
rules:{
jsonString(rule, value){
try {
JSON.parse(value);
} catch (err) {
return this.gettext('must be json string'); //here will call ctx.gettext
}
}
}
});
}
```

## Questions & Suggestions
Expand Down
28 changes: 0 additions & 28 deletions app.js

This file was deleted.

17 changes: 16 additions & 1 deletion app/extend/context.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
'use strict';

const Parameter = require('parameter');
const VALIDATOR = Symbol('Context#validator');
module.exports = {
get validator() {
if (!this[VALIDATOR]) {
const config = this.app.config.validate || {};
Object.assign(config, {
translate: this.gettext.bind(this),
runfan marked this conversation as resolved.
Show resolved Hide resolved
});
this[VALIDATOR] = new Parameter(config);
config.rules && Object.keys(config.rules).forEach(key => {
this[VALIDATOR].addRule(key, config.rules[key].bind(this));
});
}
return this[VALIDATOR];
},
/**
* validate data with rules
*
Expand All @@ -9,7 +24,7 @@ module.exports = {
*/
validate(rules, data) {
data = data || this.request.body;
const errors = this.app.validator.validate(rules, data);
const errors = this.validator.validate(rules, data);
if (errors) {
this.throw(422, 'Validation Failed', {
code: 'invalid_param',
Expand Down
6 changes: 0 additions & 6 deletions config/config.default.js

This file was deleted.

Loading