Skip to main content

Typescript support

Codehooks.io supports Typescript. This example shows how easy it is to use Typescript to create serverless functions.

  1. Start with creating a new project using the coho create CLI command.
  2. Change to the project directory and install npm i codehooks-js -s.
  3. Rename the autogenerated index.js file to index.ts. That's it. You are now using Typescript as a language.

In the following example we create two files; index.ts with two serverless API functions and sum.ts with one exported function.

import app from 'codehooks-js';
import { sum } from './sum';

function helloFunc(req: any, res: any){
res.end(`Typescript sum is ${sum(42, 42)}`);
}

app.get('/helloworld', helloFunc);
app.all('/echo', (req: any, res: any) => {
res.end(JSON.stringify(req, null, " ")); // format JSON string nicely
})

export default app.init();
export function sum(a: number, b: number): number {
return a + b;
}

Deploy with the CLI command coho deploy.

Run coho info to see your API token.

Testing the helloworld API with curl

Shell command
curl https://<PROJECT NAME>.api.codehooks.io/dev/helloworld -H 'x-apikey: <API-TOKEN>'
Output
Typescript sum is 84

Testing the echo API with curl

Shell command
curl https://<PROJECT NAME>.api.codehooks.io/dev/echo -H 'x-apikey: <API-TOKEN>'
Example output
{
"hostname": "myproject-abcd.api.codehooks.io",
"headers": {
"host": "myproject-abcd.api.codehooks.io",
"user-agent": "curl/7.77.0",
"accept": "*/*",
"x-apikey": "6e111ea6-6b3a-412d-8f6b-061c816c67c8"
},
"query": {},
"path": "/dev/echo",
"apiPath": "/echo",
"originalUrl": "/dev/echo",
"params": null,
"body": {},
"method": "GET"
}