@@ -16,11 +16,39 @@ export enum StreamOperation {
1616
1717export type StreamProperties = Todo
1818
19- export default class Stream {
19+ const VALID_FIELD_TYPES = [ 'number' , 'string' , 'boolean' , 'list' , 'map' ] as const
20+
21+ type Field = {
22+ name : string ;
23+ type : typeof VALID_FIELD_TYPES [ number ] ;
24+ }
2025
26+ function getFieldType ( value : any ) : ( Field [ 'type' ] | undefined ) {
27+ const type = typeof value
28+ switch ( true ) {
29+ case Array . isArray ( value ) : {
30+ return 'list'
31+ }
32+ case type === 'object' : {
33+ return 'map'
34+ }
35+ case ( VALID_FIELD_TYPES as ReadonlyArray < string > ) . includes ( type ) : {
36+ // see https://github.com/microsoft/TypeScript/issues/36275
37+ return type as Field [ 'type' ]
38+ }
39+ default : {
40+ return undefined
41+ }
42+ }
43+ }
44+
45+ export default class Stream {
2146 // TODO add field definitions for all fields
2247 // @ts -expect-error
2348 id : string
49+ config : {
50+ fields : Field [ ] ;
51+ } = { fields : [ ] }
2452 _client : StreamrClient
2553
2654 constructor ( client : StreamrClient , props : StreamProperties ) {
@@ -132,31 +160,24 @@ export default class Stream {
132160 last : 1 ,
133161 } ,
134162 } )
163+
135164 const receivedMsgs = await sub . collect ( )
136165
137- if ( receivedMsgs . length > 0 ) {
138- const lastMessage = receivedMsgs [ 0 ]
139- const fields = [ ]
140-
141- Object . keys ( lastMessage ) . forEach ( ( key ) => {
142- let type
143- if ( Array . isArray ( lastMessage [ key ] ) ) {
144- type = 'list'
145- } else if ( ( typeof lastMessage [ key ] ) === 'object' ) {
146- type = 'map'
147- } else {
148- type = typeof lastMessage [ key ]
149- }
150- fields . push ( {
151- name : key ,
152- type,
153- } )
154- } )
166+ if ( ! receivedMsgs . length ) { return }
155167
156- // Save field config back to the stream
157- this . config . fields = fields
158- await this . update ( )
159- }
168+ const [ lastMessage ] = receivedMsgs
169+
170+ const fields = Object . entries ( lastMessage ) . map ( ( [ name , value ] ) => {
171+ const type = getFieldType ( value )
172+ return ! ! type && {
173+ name,
174+ type,
175+ }
176+ } ) . filter ( Boolean ) as Field [ ] // see https://github.com/microsoft/TypeScript/issues/30621
177+
178+ // Save field config back to the stream
179+ this . config . fields = fields
180+ await this . update ( )
160181 }
161182
162183 async addToStorageNode ( address : string ) {
0 commit comments