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: add Schema.bytes #300

Merged
merged 1 commit into from
May 2, 2023
Merged
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
30 changes: 29 additions & 1 deletion packages/core/src/schema/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -920,6 +920,28 @@ class AnyString extends UnknownString {
const anyString = new AnyString()
export const string = () => anyString

/**
* @template [I=unknown]
* @extends {API<Uint8Array, I, void>}
*/
class BytesSchema extends API {
/**
* @param {I} input
* @returns {Schema.ReadResult<Uint8Array>}
*/
readWith(input) {
if (input instanceof Uint8Array) {
return { ok: input }
} else {
return typeError({ expect: 'Uint8Array', actual: input })
}
}
}

/** @type {Schema.Schema<Uint8Array, unknown>} */
export const Bytes = new BytesSchema()
export const bytes = () => Bytes

/**
* @template {string} Prefix
* @template {string} Body
Expand Down Expand Up @@ -1380,7 +1402,13 @@ const displayTypeName = value => {
case 'undefined':
return String(value)
case 'object':
return value === null ? 'null' : Array.isArray(value) ? 'array' : 'object'
return value === null
? 'null'
: Array.isArray(value)
? 'array'
: Symbol.toStringTag in /** @type {object} */ (value)
? value[Symbol.toStringTag]
: 'object'
default:
return type
}
Expand Down
21 changes: 21 additions & 0 deletions packages/core/test/schema.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -657,3 +657,24 @@ test('record defaults', () => {
end: { x: 1, y: 3 },
})
})

test('bytes schema', () => {
const schema = Schema.bytes()
matchError(schema.read(undefined), /expect.* Uint8Array .* got undefined/is)

const bytes = new Uint8Array([1, 2, 3])

assert.equal(schema.read(bytes).ok, bytes, 'returns same bytes back')

matchError(
schema.read(bytes.buffer),
/expect.* Uint8Array .* got ArrayBuffer/is
)

matchError(
schema.read(new Int8Array(bytes.buffer)),
/expect.* Uint8Array .* got Int8Array/is
)

matchError(schema.read([...bytes]), /expect.* Uint8Array .* got array/is)
})