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

Configurable schema validation #11

Open
wants to merge 2 commits into
base: main
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,5 @@ dist
.pnp.*

package-lock.json
.vscode
test-storage
3 changes: 3 additions & 0 deletions example.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const Hyperschema = require('.')

const schema = Hyperschema.from('./spec')
const ns1 = schema.namespace('namespace-1')
ns1.require('./helpers.js')

const ns2 = schema.namespace('namespace-2')

ns2.register({
Expand Down Expand Up @@ -60,6 +62,7 @@ ns1.register({
ns1.register({
name: 'basic-struct',
flagsPosition: 0,
validator: 'basicStructValidator',
fields: [
{
name: 'id',
Expand Down
4 changes: 4 additions & 0 deletions helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
exports.basicStructValidator = (state, m) => {
if (!m.id) throw new Error('id is required')
if (!m.basicString) throw new Error('basicString is required')
}
11 changes: 11 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ class Struct extends ResolvedType {
super(hyperschema, fqn, description, existing)
this.isStruct = true
this.default = null
this.validator = description.validator

this.fields = []
this.fieldsByName = new Map()
Expand Down Expand Up @@ -188,6 +189,10 @@ class Struct extends ResolvedType {
}
}

getNamespace () {
return this.hyperschema.namespaces.get(this.namespace)
}

toJSON () {
return {
name: this.name,
Expand All @@ -203,6 +208,12 @@ class HyperschemaNamespace {
constructor (hyperschema, name) {
this.hyperschema = hyperschema
this.name = name
this.helpers = null
this.id = hyperschema.namespaces.size
}

require (filename) {
this.helpers = p.resolve(filename)
}

register (description) {
Expand Down
20 changes: 18 additions & 2 deletions lib/codegen.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const gen = require('generate-object-property')
const s = require('generate-string')
const p = require('path')

module.exports = function generateSchema (hyperschema) {
const structs = []
Expand Down Expand Up @@ -33,6 +34,13 @@ module.exports = function generateSchema (hyperschema) {
str += 'let version = VERSION\n'
str += '\n'

for (const ns of hyperschema.namespaces.values()) {
if (!ns.helpers) continue
const helpers = p.relative(p.resolve(hyperschema.dir), ns.helpers).replaceAll('\\', '/')
str += `const helpers${ns.id} = require('${helpers}')\n`
str += '\n'
}

for (let i = 0; i < structs.length; i++) {
const struct = structs[i]
const { encoder } = structsByName.get(struct.fqn)
Expand Down Expand Up @@ -102,7 +110,13 @@ module.exports = function generateSchema (hyperschema) {
str += '\n'
}

const preencode = generateEncode(struct, { preencode: true })
if (struct.validator) {
str += `// ${struct.fqn}.validator\n`
str += `const ${id}_validator = ${gen('helpers' + struct.getNamespace().id, struct.validator)}\n`
str += '\n'
}

const preencode = generateEncode(struct, { id, preencode: true })
const encode = generateEncode(struct)
const decode = generateDecode(struct)
str += `// ${struct.fqn}\n`
Expand All @@ -119,10 +133,12 @@ module.exports = function generateSchema (hyperschema) {
str += '}\n'
return str

function generateEncode (struct, { preencode = false } = {}) {
function generateEncode (struct, { id, preencode = false } = {}) {
const fn = preencode ? 'preencode' : 'encode'
let str = ''

str = preencode && struct.validator ? ` ${id}_validator(state, m)\n` : ''

if (struct.optionals.length >= 1) str += ' let flags = 0\n'
for (const field of struct.optionals) {
str += ` ${vPrefix(field.version, gen('m', field.name))} flags |= ${field.flag}`
Expand Down
34 changes: 34 additions & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,40 @@ test('basic required field missing', async t => {
}
})

test('basic required field missing with validation', async t => {
const schema = await createTestSchema(t)

await schema.rebuild(schema => {
const ns = schema.namespace('test')
ns.require('test/helpers/index.js')
ns.register({
name: 'test-struct',
validator: 'testValidator',
fields: [
{
name: 'field1',
type: 'string',
required: true
}
]
})
})

t.is(schema.json.version, 1)
t.is(schema.module.version, 1)

{
const enc = schema.module.resolveStruct('@test/test-struct')
const missingRequired = { field2: 'badField' }
try {
c.encode(enc, missingRequired)
t.fail('expected error')
} catch (e) {
t.is(e.message, 'field1 is required')
}
}
})

test('basic nested struct, version bump', async t => {
const schema = await createTestSchema(t)

Expand Down
7 changes: 6 additions & 1 deletion test/helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ async function createTestSchema (t) {
return new TestBuilder(dir, t)
}

function testValidator (state, m) {
if (!m.field1) throw new Error('field1 is required')
}

module.exports = {
createTestSchema
createTestSchema,
testValidator
}
Loading