17
17
18
18
import { isPrimitiveArrayEqual } from '../util/array' ;
19
19
import { 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' ;
20
23
21
24
/**
22
25
* Represents a vector type in Firestore documents.
@@ -50,6 +53,12 @@ export class VectorValue {
50
53
return isPrimitiveArrayEqual ( this . _values , other . _values ) ;
51
54
}
52
55
56
+ static _jsonSchemaVersion : string = 'firestore/vectorValue/1.0' ;
57
+ static _jsonSchema = {
58
+ type : property ( 'string' , VectorValue . _jsonSchemaVersion ) ,
59
+ vectorValues : property ( 'object' )
60
+ } ;
61
+
53
62
/** Returns a JSON-serializable representation of this `VectorValue` instance. */
54
63
toJSON ( ) : object {
55
64
return {
@@ -59,39 +68,21 @@ export class VectorValue {
59
68
}
60
69
/** Builds a `Bytes` instance from a JSON serialized version of `Bytes`. */
61
70
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 ) ;
90
77
}
78
+ throw new FirestoreError (
79
+ Code . INVALID_ARGUMENT ,
80
+ "Expected 'vectorValues' field to be a number array"
81
+ ) ;
91
82
}
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
+ ) ;
96
87
}
97
88
}
0 commit comments