Create an executable
Customizing your backend provides a number of different benefits. In the example below, we show one particular use case, exposing a backend function that can be called directly from the client.
When working with Squid executables, it's important to keep in mind that these backend functions can be accessed directly from the client and have unlimited permissions to access backend resources and secrets. This means that you need to take extra care to make sure that only authorized users are able to execute them.
To create your first executable, follow these steps:
Create a function decorated with @executable
inside example-service.ts
in your backend project:
import { executable, SquidService } from '@squidcloud/backend';
type Announcement = { announcement: string };
export class ExampleService extends SquidService {
@executable()
async createAnnouncement(announcementText: string): Promise<string> {
const id = crypto.randomUUID();
const doc = this.squid.collection<Announcement>('announcements').doc(id);
await doc.insert({ announcement: announcementText });
return id;
}
}
To allow Squid to discover the executable and the rest of the functions in the same service, make sure the service is exported in the service/index.ts
file:
export * from './example-service';
Deploy your backend project using the Squid CLI:
squid deploy --apiKey YOUR_API_KEY --environmentId TARGET_ENVIRONMENT_ID
Call the executable in your client code:
const announcementId = await squid.executeFunction('createAnnouncement', 'Hello world!');
console.log(announcementId); // Will print the newly created announcement ID
What's going on here?
Once your backend project has been deployed, the Squid Server can send requests to your backend functions, execute them, and return their responses.
In this example, after calling executeFunction('createAnnouncement', ...)
on the client, the Squid Server
searches for an @executable
function named createAnnouncement
in your backend project and executes it with the
provided parameters. Once the execution is complete, the response, in this case the announcement ID
, is sent back to
the client.
For more information visit the Executables section in the docs.