1717
1818import { isPrimitiveArrayEqual } from '../util/array' ;
1919import { Code , FirestoreError } from '../util/error' ;
20+ // API extractor fails importing 'property' unless we also explicitly import 'Property'.
21+ // eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts
22+ import { Property , property , validateJSON } from '../util/json_validation' ;
2023
2124/**
2225 * Represents a vector type in Firestore documents.
@@ -50,6 +53,12 @@ export class VectorValue {
5053 return isPrimitiveArrayEqual ( this . _values , other . _values ) ;
5154 }
5255
56+ static _jsonSchemaVersion : string = 'firestore/vectorValue/1.0' ;
57+ static _jsonSchema = {
58+ type : property ( 'string' , VectorValue . _jsonSchemaVersion ) ,
59+ vectorValues : property ( 'object' )
60+ } ;
61+
5362 /** Returns a JSON-serializable representation of this `VectorValue` instance. */
5463 toJSON ( ) : object {
5564 return {
@@ -59,39 +68,21 @@ export class VectorValue {
5968 }
6069 /** Builds a `Bytes` instance from a JSON serialized version of `Bytes`. */
6170 static fromJSON ( json : object ) : VectorValue {
62- const requiredFields = [ 'type' , 'vectorValues' ] ;
63- let error : string | undefined = undefined ;
64- let data : number [ ] = [ ] ;
65- for ( const key of requiredFields ) {
66- if ( ! ( key in json ) ) {
67- error = `json missing required field: ${ key } ` ;
68- }
69- // eslint-disable-next-line @typescript-eslint/no-explicit-any
70- const value = ( json as any ) [ key ] ;
71- if ( key === 'type' ) {
72- if ( typeof value !== 'string' ) {
73- error = `json field 'type' must be a string.` ;
74- break ;
75- } else if ( value !== 'firestore/vectorvalue/1.0' ) {
76- error = "Expected 'type' field to equal 'firestore/vectorvalue/1.0'" ;
77- break ;
78- }
79- } else {
80- // First, confirm it's actually an array
81- if (
82- Array . isArray ( value ) &&
83- value . every ( element => typeof element === 'number' )
84- ) {
85- data = value ;
86- } else {
87- error = "Expected 'vectorValues' field to be a number array" ;
88- break ;
89- }
71+ if ( validateJSON ( json , VectorValue . _jsonSchema ) ) {
72+ if (
73+ Array . isArray ( json . vectorValues ) &&
74+ json . vectorValues . every ( element => typeof element === 'number' )
75+ ) {
76+ return new VectorValue ( json . vectorValues ) ;
9077 }
78+ throw new FirestoreError (
79+ Code . INVALID_ARGUMENT ,
80+ "Expected 'vectorValues' field to be a number array"
81+ ) ;
9182 }
92- if ( error ) {
93- throw new FirestoreError ( Code . INVALID_ARGUMENT , error ) ;
94- }
95- return new VectorValue ( data ) ;
83+ throw new FirestoreError (
84+ Code . INTERNAL ,
85+ 'Unexpected error creating Timestamp from JSON.'
86+ ) ;
9687 }
9788}
0 commit comments