orbit-type-generator
v1.0.0-alpha.4
Published
Create TypeScript definition file from a Orbit.js Schema definition
Downloads
6
Readme
orbit-type-generator
TypeScript type generator for Orbit schema definitions.
API
import { generateTypes } from 'orbit-type-generator'
const definition = {
models: {
user: {
attributes: {
username: { type: 'string' }
}
}
}
}
const schema = new Schema(definition)
const types = generateTypes(schema)
The types
variable now contains this code:
import { Record, RecordIdentity, RecordRelationship, RecordHasOneRelationship, RecordHasManyRelationship } from "@orbit/data";
import { Dict } from "@orbit/utils";
export interface UserRecord extends Record, UserRecordIdentity {
attributes?: UserAttributes;
relationships?: undefined;
}
export interface UserRecordIdentity extends RecordIdentity {
type: "user";
id: string;
}
export interface UserAttributes extends Dict<any> {
username: string;
}
CLI
If you have a file schema.js
:
export default {
models: {
user: {
attributes: {
username: { type: 'string' }
}
}
}
}
you can generate the types with:
orbit-type-generator schema.js > models.d.ts
Advanced
Using TypeScript types
You can type attributes using TypeScript types or interfaces.
The generator will automatically import the type based on a resolved
tsconfig.json
in the directory you're executing from.
const definition = {
models: {
user: {
attributes: {
permission: { type: 'UserPermission' }
}
}
}
}
You can optionally specify a fallback type to use if TypeScript can't resolve the specified type:
const definition = {
models: {
user: {
attributes: {
permission: { type: 'string', ts: 'UserPermission' }
}
}
}
}
const schema = new Schema(definition)
const types = generateTypes(schema, { tsProperty: 'ts' })
Specify a different base directory
If you want your imports to be relative to a different directory than the directory you're executing from, use:
const types = generateTypes(schema, {
basePath: path.resolve(__dirname, 'src')
})
Todo
- [ ] Properly generate types for relationships
- [ ] Support .ts files in CLI using on-the-fly compiling