Skip to content
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
15 changes: 14 additions & 1 deletion src/factories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.

import { Field, Schema } from './schema.js';
import { AnonymousField, Field, Schema } from './schema.js';
import * as dtypes from './type.js';
import { Data, DataProps } from './data.js';
import { BuilderType, JavaScriptDataType } from './interfaces.js';
Expand Down Expand Up @@ -270,3 +270,16 @@ export function builderThroughAsyncIterable<T extends dtypes.DataType = any, TNu
}
} as ThroughAsyncIterable<T, TNull>;
}

/**
* Helper factory to create a type-safe anonymous field.
* @param type The type of the field
* @param nullable Whether the field is nullable
* @param metadata Optional metadata for the field
* @returns An anonymous field to be used in a [FieldDictionary]{@link FieldDictionary}
*/
export const anonymousField = <T extends dtypes.DataType>(
type: T,
nullable?: boolean,
metadata?: Map<string, string>
) => ({ type, nullable, metadata }) as AnonymousField<T>;
19 changes: 17 additions & 2 deletions src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,16 @@ export class Schema<T extends TypeMap = any> {
public readonly metadataVersion: MetadataVersion;

constructor(
fields: Field<T[keyof T]>[] = [],
fields: Field<T[keyof T]>[] | FieldDictionary<T> = {} as FieldDictionary<T>,
metadata?: Map<string, string> | null,
dictionaries?: Map<number, DataType> | null,
metadataVersion = MetadataVersion.V5) {
this.fields = (fields || []) as Field<T[keyof T]>[];
if (Array.isArray(fields)) {
this.fields = fields as Field<T[keyof T]>[];
} else {
const entries = Object.entries(fields);
this.fields = entries.map(([name, field]) => new Field(name, field.type, field.nullable, field.metadata));
}
this.metadata = metadata || new Map();
if (!dictionaries) {
dictionaries = generateDictionaryMap(this.fields);
Expand Down Expand Up @@ -177,3 +182,13 @@ function generateDictionaryMap(fields: Field[], dictionaries = new Map<number, D

return dictionaries;
}

export type AnonymousField<T extends DataType> = {
readonly type: T;
readonly nullable?: boolean;
readonly metadata?: Map<string, string>;
}

export type FieldDictionary<T extends TypeMap> = {
[name in keyof T]: AnonymousField<T[name]>;
}
Loading