Coder Social home page Coder Social logo

cloudnativeentrepreneur / register-server-handlers Goto Github PK

View Code? Open in Web Editor NEW
2.0 1.0 0.0 1.93 MB

Registers a folder of handlers as HTTP POST routes on an express server - supports CloudEvent handlers as well for use with tools like KNative

JavaScript 1.76% Shell 0.32% TypeScript 97.93%
knative knative-eventing cqrs cqrs-es nodejs express

register-server-handlers's Introduction

Release codecov

register-server-handlers

Registers a folder of handlers as HTTP POST routes on a server - handlers receive commands/events in CloudEvents format.

View on npm.

Usage

Installation

npm install --save register-server-handlers

Startup

On startup, call registerHandlers

import path from 'path'
import express from 'express'
import { registerHandlers } from 'register-server-handlers'

const server = express()

export const start = async (server) => {

  // create post handlers for each file in folder src/handlers at `/<filename without extension>`
  await registerHandlers({
    server,
    path: path.resolve(process.cwd(), 'src', 'handlers'),
    handlerOptions: {
      sync: true
    }
  })

  // create post handlers for cloudevents with same handlers at `/cloudevents/<filename without extension>`
  await registerHandlers({
    server,
    path: path.resolve(process.cwd(), 'src', 'handlers'),
    cloudevents: true,
    serverPath: '/cloudevent/'
  })

  try {
    await server.listen(port)
  } catch (err) {
    server.log.error(err)
    process.exit(1)
  }
}

start(server)

This way you can write the handler logic once and handle it via direct HTTP Post or via a CloudEvent, such as when creating a Trigger for a Knative Event, or from a Command API, such as Hasura Actions.

Handlers

Each handler in the given directory must export a named function handle, and optionally, a where filter.

For example, src/handlers/example.initialize.js:

// if message.data.id is not provided, a 202 response will be sent and the handler will not execute
// makes for easy, declarative validation and unit testing
// https://github.com/knative/specs/blob/main/specs/eventing/data-plane.md#event-acknowledgement-and-delivery-retry
export const where = (message) => !!(message.data && message.data.id)

// `message` is a CloudEvent
// `type` is the file name without the extension - `example.initialize`
export const handle = async (request, reply, message, handlerOptions) => {
  const { data, type, source } = message
  const { id } = message
  const { sync } = handlerOptions
  // do stuff
  // then reply
  reply.status(200).send()
}

This will register /example.initialize as an HTTP Post endpoint.

CloudEvents

If you expect to receive messages in the CloudEvents format, you can set cloudevents: true.

await registerHandlers({
  server,
  path: path.resolve(process.cwd(), 'src', 'handlers'),
  cloudevents: true
})

serverPath

The default server path is /, which the filename without the extension is appended to.

To customize this path, set serverPath to a custom value.

For example, if you want to receive cloud events at /cloudevent/${eventname}

await registerHandlers({
  server,
  path: path.resolve(process.cwd(), 'src', 'handlers'),
  cloudevents: true,
  serverPath: '/cloudevent/'
})

knativebus

The intended usage for this is to build CQRS/ES systems with KNative. If you're interested in doing something similar, this library works well with knativebus.

Configured correctly, sending cloudevents to the cloudevent handlers via knativebus can be accomplished with:

await bus.send('example.initialize', { id: 1, name: 'Example 1' })

This would Trigger a handler on a service subscibed to the example-commands broker (see knative docs for examples of creating brokers). The handler would receive a cloudevent with type example.initialize, therefore handled by src/handlers/example.initialize.js in the above configuration.

apiVersion: eventing.knative.dev/v1
kind: Trigger
metadata:
  name: example.initialize
spec:
  broker: example-commands
  filter:
    attributes:
      type: example.initialize
  subscriber:
    ref:
{{- if .Values.knativeDeploy }}
      apiVersion: serving.knative.dev/v1
      kind: Service
      name: example-model
{{- else }}
      apiVersion: v1
      kind: Service
      name: example-model
{{- end }}
    uri: /cloudevent/example.initialize

register-server-handlers's People

Contributors

patrickleet avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar

Watchers

 avatar

register-server-handlers's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency eslint to v8.57.0
  • chore(deps): update dependency eslint to v9
  • chore(deps): update dependency husky to v9
  • chore(deps): update dependency lint-staged to v15
  • chore(deps): update typescript-eslint monorepo to v7 (major) (@typescript-eslint/eslint-plugin, @typescript-eslint/parser)
  • fix(deps): update dependency cloudevents to v8
  • πŸ” Create all rate-limited PRs at once πŸ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/codecov.yml
  • actions/checkout v2
  • actions/setup-node v2
.github/workflows/pullrequest.yml
  • actions/checkout v2
  • actions/setup-node v2
.github/workflows/release.yml
  • actions/checkout v2
  • actions/setup-node v2
npm
package.json
  • cloudevents 5.3.2
  • debug 4.3.4
  • objectify-folder 1.3.4
  • @types/debug 4.1.12
  • @types/jest 27.5.2
  • @types/lodash.clonedeep 4.5.9
  • @types/node 17.0.45
  • @typescript-eslint/eslint-plugin 5.62.0
  • @typescript-eslint/parser 5.62.0
  • codecov 3.8.3
  • eslint 8.56.0
  • eslint-config-prettier 8.10.0
  • eslint-plugin-prettier 4.2.1
  • husky 7.0.4
  • jest 27.5.1
  • lint-staged 13.3.0
  • prettier 2.8.8
  • semantic-release 20.1.3
  • ts-jest 27.1.5
  • typescript 4.8.4
  • express 4.x

  • Check this box to trigger a request for Renovate to run again on this repository

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (github>whitesource/merge-confidence:beta)

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.