1 Context:
In this example, we will implement our own TypeScript backend function that looks up and returns the weather at a specific point on the globe; for this task, we will create a new endpoint in our TypeScript Node server (Nano)
2 Step by step guide:
- In your ProCode Workspace create a new folder
src/nano/src/service/training/
- Create a new file in that folder
src/nano/src/service/training/getweather.ts
- Add an empty function to the file:
- Add the logic to fetch the data and return it to the function:
- The Nano server will automatically detect these changes and make them available without any additional actions; you can now call the service from the browser with the following call:
import type { HandlerArgs, Result } from '@/core/handler/handler.types';
import { successResult, errorResult } from '@/core/handler/handler.utils';
import { http } from '@/core/http/http.utils';
import { addService } from '@/core/service/service.utils';
interface Query {}
export async function getweather(args: HandlerArgs<Query>): Promise<Result> {
}
// register the service into nano
addService({ path: __filename, handler: getweather });
interface Query {
lat: string;
lon: string;
}
export async function getWeather(args: HandlerArgs<Query>): Promise<Result> {
try {
const { lat = '52', lon = '7.6' } = args.query;
const url = `https://api.brightsky.dev/weather?lat=${lat}&lon=${lon}&date=2023-04-05`;
const { data } = await http.get(url);
return successResult({ message: 'All good!', data });
} catch (error) {
return errorResult({
message: 'Not so good!',
errorCode: error?.code ?? 'unknown',
});
}
}
b1.v1.App.invokeServerTask({
name: "training/getweather",
methodType: "nano",
paramObj: { query: { lat: 52, lon: 10 } }
})
Full Code Example:
import type { HandlerArgs, Result } from '@/core/handler/handler.types';
import { successResult, errorResult } from '@/core/handler/handler.utils';
import { http } from '@/core/http/http.utils';
import { addService } from '@/core/service/service.utils';
interface Query {
lat: string;
lon: string;
}
export async function getWeather(args: HandlerArgs<Query>): Promise<Result> {
try {
const { lat = '52', lon = '7.6' } = args.query;
const url = `https://api.brightsky.dev/weather?lat=${lat}&lon=${lon}&date=2023-04-05`;
const { data } = await http.get(url);
return successResult({ message: 'All good!', data });
} catch (error) {
return errorResult({
message: 'Not so good!',
errorCode: error?.code ?? 'unknown',
});
}
}
addService({ path: __filename, handler: getWeather });
3 Explanation:
The TypeScript backend functions allow you full access to a Node server, where you can implement any logic required. From simple tasks to complex calculations.