REST API Client in Node.js Environment
When using JavaScript customization in kintone, you can directly write the JavaScript to be embedded, but by utilizing Node.js, you can use various modules available in kintone.
@kintone/rest-api-client is one of them, a module officially developed by Cybozu Inc. to make using the REST API easier.
This time, I will introduce the points I pay attention to when utilizing the REST API Client.
Use as a Singleton
When using the REST API Client, import the class from the module and create a new instance as shown below.
import { KintoneRestAPIClient } from '@kintone/rest-api-client';
const client = new KintoneRestAPIClient({
baseUrl: https://xxxxxxxx.cybozu.com,
auth: {
username: xxxxxxxxxxxx,
password: xxxxxxxxxxxx,
},
});
const response = await client.record.getAllRecordsWithCursor({ app: 16 });
However, there may be cases where you want to repeatedly retrieve or update records from multiple apps within the functionality you want to implement.
When using an API token, you need to create an instance for each app, but when using a password, it is convenient to define the instance as a singleton.
Create a file like kintone-api-client.js
and write only the code to export the instance.
It is convenient to define environment variables with dotenv.
import { KintoneRestAPIClient } from '@kintone/rest-api-client';
//_If_using_username_and_password
export const kintoneClient = new KintoneRestAPIClient({
baseUrl: process.env.KINTONE_BASE_URL,
auth: {
username: process.env.KINTONE_USERNAME,
password: process.env.KINTONE_PASSWORD,
},
});
//_If_using_API_token
export const kintoneClient = new KintoneRestAPIClient({
baseUrl: process.env.KINTONE_BASE_URL,
auth: { apiToken: process.env.KINTONE_API_TOKEN },
});
When actually using it, import the instance from the file defined earlier.
import { kintoneClient } from './kintone-api-client';
const response = await kintoneClient.record.getAllRecordsWithCursor({ app: 16 });
Support for Guest Spaces
The kintone REST API also supports guest spaces, and you can access the target guest space by specifying guestSpaceId
in the constructor arguments.
Assuming that the place where it is executed is a guest space, I will introduce a method to automatically determine the guest space.
Since the automatic determination logic is not officially provided, it may stop working due to updates.
Although it is written in TypeScript, if you are using JavaScript, please remove ConstructorParameters<typeof KintoneRestAPIClient>
.
import { KintoneRestAPIClient } from '@kintone/rest-api-client';
class FlexKintone extends KintoneRestAPIClient {
constructor(...options: ConstructorParameters<typeof KintoneRestAPIClient>) {
const url = kintone.api.url('/k/v1/app', true);
const found = url.match(/k\/guest\/([0-9]+)\//);
if (found && found.length > 1) {
super({
guestSpaceId: found[1],
...(options[0] || {}),
});
return;
}
super(...options);
}
}