Node.js API reference

App

The App class represents a Teo server app.

constructor

Create an app.

Examples

Create an app
const app = new App()

mainNamespace

Retrieve the main namespace from the app. Namespace is where models, handlers, decorators and pipeline items are defined. See Namespace.

Examples

Retrieve the main namespace
const mainNamespace = app.mainNamespace()

setup

Attach some code to run after the database is connected. The parameter Teo is in generated entities.

Examples

Run custom setup code
app.setup(async (teo: Teo) => {
    await teo.transaction(async (teo: Teo) => {
      // perform something within this transaction
    })
})

program

Define a custom program to run with Teo CLI. The parameter Teo is in generated entities.

Examples

Define a custom program
app.program("mycode", "description", async (teo: Teo) => {
    // do something with the data...
})

run

Start the Teo server app.

Example

Run an server app
await app.run()

Namespace

Namespace is where things are defined and organized.

isMain

Whether the namespace is the main namespace.

isStd

Whether the namespace is the builtin standard namespace.

path

Get the namespace's path.

Example

Namespace's path

const namespacePath: string[] = namespace.path()

namespace

Get the namespace's child namespace by name or None.

namespaceOrCreate

Get the namespace's child namespace by name. If not present, create and return.

namespaceAtPath

Get the namespace's child namespace at path.

namespaceOrCreateAtPath

The the namespace's child namespace at path. If not present, create and return.

defineModelDecorator

Define a new model decorator on a namespace.

Example

Define a custom model decorator
app.mainNamespace().defineModelDecorator("myModelDecorator", (model) => {
    model.setData("myData", "myValue")
})

defineModelFieldDecorator

Define a new model field decorator on a namespace.

Example

Define a custom model field decorator
app.mainNamespace().defineModelFieldDecorator("myModelFieldDecorator", (field) => {
    field.setData("myData", "myValue")
})

defineModelRelationDecorator

Define a new model relation decorator on a namespace.

Example

Define a custom model relation decorator
app.mainNamespace().defineModelRelationDecorator("myModelRelationDecorator", (relation) => {
    relation.setData("myData", "myValue")
})

defineModelPropertyDecorator

Define a new model property decorator on a namespace.

Example

Define a custom model property decorator
app.mainNamespace().defineModelPropertyDecorator("myModelPropertyDecorator", (property) => {
    property.setData("myData", "myValue")
})

definePipelineItem

Define a custom pipeline item on a namespace.

Example

Define a custom pipeline item
app.mainNamespace().definePipelineItem("replaceComWithIo", async (input: string) => {
    return input.replace(/com$/, 'io')
})

defineTransformPipelineItem

Define a transformer pipeline item. This is a shortcut to definePipelineItem.

Example

Define a custom transformer
app.mainNamespace().defineTransformPipelineItem("addOne", (i: number) => i + 1)

defineValidatorPipelineItem

Register a custom validate function.

Examples

Define a custom validator pipeline item with bool return value
app.mainNamespace().defineValidatorPipelineItem("myValidator", (input: string) => {
    return input.endsWith(".")
})
Define a custom validator pipeline item with string return value
app.mainNamespace().defineValiatorPipelineItem("myValidator", (input: string) => {
    if (!input.endsWith(".")) {
      return "value is invalid"
    }
})
Define a custom validator pipeline item which errors
app.mainNamespace().defineValidatorPipelineItem("myValidator", (input: string) => {
    if (!input.endsWith(".")) {
      throw Error("value is invalid")
    }
})

defineCallbackPipelineItem

Define a callback pipeline item. This is a shortcut to definePipelineItem.

Example

Define a custom callback pipeline item
app.mainNamespace().defineCallbackPipelineItem("myCallback", (_value: any, user: User) => {
    // do something with the user object...
})
Define a custom callback pipeline item which errors
app.mainNamespace().defineCallbackPipelineItem("myCallback", (_value: any, user: User) => {
    if (user.email.endsWith('.com')) {
        throw Error("value is invalid")
    }
    // do something with the user object...
})

defineComparePipelineItem

Define a compare pipeline item. This is a shortcut to definePipelineItem.

Example

Define a custom compare pipeline item

app.mainNamespace().defineComparePipelineItem("myCallback", (old: string, new: string) => {
    // do some callback with the old value and the new value
    // return a validation result if the new value is invalid
})

defineMiddleware

Define a middleware on a namespace.

Example

Define a custom middleware
app.mainNamespace().defineMiddleware("logBeforeAfter", (args) => {
    return async (ctx, next) => {
        console.log("before request", ctx)
        const res = await next(ctx)
        console.log("after request", res)
        return res
    }
})

defineHandler

Define a custom route handler on a namespace.

Example

Define a custom route handler
app.mainNamespace().defineHandler("myHandler", async (ctx) => {
    const teo: Teo = ctx.teo()
    const user = await teo.user.findFirst({})
    return Response.teon(await user?.toTeon())
})

defineHandlerGroup

Define a handler group on a namespace.

Example

Define a custom handler group
app.mainNamespace().defineHandlerGroup("MyHandlerGroup", (group: HandlerGroup) => {
    group.defineHandler("myHandler", async (ctx: RequestCtx) => {
        const teo: Teo = ctx.teo()
        const user = await teo.user.findFirst({})
        return Response.teon(await user?.toTeon())
    })
})

defineModelHandlerGroup

Define model handlers on a namespace.

Example

Define a custom model handler group
app.mainNamespace().defineHandlerGroup("User", (group: HandlerGroup) => {
    group.defineHandler("grabOne", async (ctx) => {
        const teo: Teo = ctx.teo()
        const user = await teo.user.findFirst({})
        return Response.teon(await user?.toTeon())
    })
})

HandlerGroup

A handler group is a container for defining custom route handlers.

defineHandler

Define a custom route handler on a handler group.

Example

Define a custom route handler
app.mainNamespace().defineHandlerGroup("MyHandlerGroup", (group: HandlerGroup) => {
    group.defineHandler("myHandler", async (ctx: RequestCtx) => {
        const teo: Teo = ctx.teo()
        const user = await teo.user.findFirst({})
        return Response.teon(await user?.toTeon())
    })
})

Request

A request represents an HTTP request.

method

Retrieve the request's method.

path

Retrieve the request's path.

queryString

Retrieve the request's query string.

contentType

Retrieve the request's content type.

headers

Retrieve the request's headers.

ReadOnlyHeaderMap

The ReadOnlyHeaderMap class represents readonly headers on a request.

keys

Retrieve the header map's keys.

len

Retrieve the length of the header map.

containsKey

Whether the headers contain a specific key.

get

Retrieve the value of a header entry by key.

Response

The Response class represents an HTTP response.

empty

Create an empty response.

Example

Create an empty response
Response.empty()

string

Create a string response.

Example

Create a string response
Response.string("Hello, world!", "text/plain")

teon

Create a Teon response.

html

Create an HTML response.

Example

Create an HTML response
Response.html("<html><body>Hello, world!</body></html>")

data

Create a Teon response which contains a data field.

dataMeta

Create a Teon response which contains a data field and a meta field.

file

Create a file response.

Example

Create a file response
Response.file("a.txt")

redirect

Create a redirect response.

Example

Create a redirect response
Response.redirect("https://example.com")

setCode

Set the response code.

code

Retrieve the response code.

headers

Retrieve the response headers.

isEmpty

Whether the response body is empty.

isFile

Whether the response body is a file.

getFile

Retrieve the response file path. If the response' type is not file, undefined is returned.

isText

Whether the response body is text.

getText

Retrieve the response text. If the response' type is not text, undefined is returned.

isTeon

Whether the response body is a teon object.

getTeon

Retrieve the response Teon value. If the response' type is not Teon, undefined is returned.

ReadWriteHeaderMap

The ReadWriteHeaderMap class represents readwrite headers on a response.

keys

Retrieve the header map's keys.

len

Retrieve the length of the header map.

containsKey

Whether the headers contain a specific key.

get

Retrieve the value of a header entry by key.

set

Set a new value of a header entry at key.

Entity model

API documentation for generated model entities.

findMany

Find many objects with params same as findMany handler.

Signature

async function findMany(finder?: ModelFindManyArgs): Promise<Model[]>

Arguments

NameRequiredTypeDescription
finderYesModelFindManyArgsThe finder

Examples

Find all users
const users = await teo.user.findMany()
Find users filtered by name
const users = await teo.user.findMany({
    where: {
      name: 'John'
    }
})
Find users ordered by createdAt
const users = await teo.user.findMany({
    orderBy: {
      createdAt: 'desc'
    }
})
Find users with posts
const users = await teo.user.findMany({
    include: {
      posts: true
    }
})

findUnique

Find a unique object with params same as findUnique handler.

Signature

async function findUnique(finder: ModelFindUniqueArgs): Promise<Model | null>

Arguments

NameRequiredTypeDescription
finderYesModelFindUniqueArgsThe finder

Examples

Find a unique user
const user = await teo.user.findUnique({
  where: {
    id: 1
  }
})

findFirst

Find an object with params same as findFirst handler.

Signature

async function findFirst(finder: ModelFindManyArgs): Promise<Model | null>

Arguments

NameRequiredTypeDescription
finderYesModelFindManyArgsThe finder

Examples

Find a user
const user = await teo.user.findFirst({
  where: {
    age: 20
  }
})

count

Count objects or fields in the model.

Signature

async function count(query: ModelCountArgs) -> Promise<number | ModelCountResult>

Arguments

NameRequiredTypeDescription
queryYesModelCountArgsThe finder

Examples

Count objects
const count_result = await teo.user.count({})

aggregate

Aggregate on the model.

Signature

async function aggregate(query: ModelAggregateArgs): Promise<ModelAggregateResult>

Arguments

NameRequiredTypeDescription
queryYes&ValueThe finder

Examples

Aggregate on the model
const aggregate_result = await teo.user.aggregate({})

groupBy

Group by on the model.

Signature

async function aggregate(query: ModelGroupByArgs) -> Promise<ModelAggregateResult[]>

Arguments

NameRequiredTypeDescription
queryYes&ValueThe finder

Example

Group by on the model
const group_by_result = await teo.record.group_by({
    "by": "name"
})

create

Create a new entity.

Signature

static async function create(input: ModelCreateArgs): Promise<Model>

Arguments

NameRequiredTypeDescription
inputNoModelCreateArgsThe create data

Examples

Create a new Post
const post = await teo.post.create({ title: "Post 1" })

Entity object

isNew

Returns true if object is new.

Examples

Check whether a post is new
const isNew = post.isNew

isModified

Returns true if object is modified.

Examples

Check if a post is modified
const isModified = post.isModified

set

Set values to an object. The onSet pipeline is triggered.

Signature

async function set(values: ModelUpdateInput): void

Arguments

NameRequiredTypeDescription
valuesYesModelUpdateInputThe set data

Examples

Set values to a user
await user.set({ "name": "Peter", "age": 15 })

update

Update values on an object.

Signature

async function update(values?: ModelScalarUpdateInput): void

Arguments

NameRequiredTypeDescription
valuesNoModelScalarUpdateInputThe update data

Examples

Update values on a user
await user.update({ "name": "Peter", "age": 15 })

save

Save an object.

Signature

async function save(): void

Examples

Save a post
await post.save()

delete

Delete an object.

Signature

async function delete(): void

Examples

Delete a post
await post.delete()

toTeon

Convert the object to a teon result value.

Signature

async function to_teon() -> ModelResult

Examples

Convert an object to its result type
const value = await object.toTeon()