Skip to content

Commit

Permalink
update: add rules service
Browse files Browse the repository at this point in the history
Signed-off-by: ianmuchyri <[email protected]>
  • Loading branch information
ianmuchyri committed Jan 8, 2025
1 parent e0d4ea6 commit 893a8f6
Show file tree
Hide file tree
Showing 6 changed files with 349 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/violet-jokes-explain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@absmach/magistrala-sdk": minor
---

add rules service to the sdk
58 changes: 58 additions & 0 deletions examples/re.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import SDK from "../src/sdk";

const defaultUrl = "http://localhost";

const mySdk = new SDK({
rulesUrl: `${defaultUrl}:9008`,
});

const token = "<token>";
const domainId = "<domainId>";

mySdk.Rules.CreateRule({ name: "<ruleName>" }, domainId, token)
.then((response: any) => {
console.log("response:", response);
})
.catch((error) => {
console.error(error);
});

mySdk.Rules.ListRules({ offset: 0, limit: 10 }, domainId, token)
.then((response: any) => {
console.log("response: ", response);
})
.catch((error) => {
console.error(error);
});

mySdk.Rules.ViewRule("<ruleId>", domainId, token)
.then((response: any) => {
console.log(response);
})
.catch((error: any) => {
console.error(error);
});

mySdk.Rules.UpdateRule(
{
id: "<ruleId>",
name: "<updatedName>",
logic: { type: 1, value: "<value>" },
},
domainId,
token
)
.then((response: any) => {
console.log("response:", response);
})
.catch((error) => {
console.error(error);
});

mySdk.Rules.DeleteRule("<ruleId>", domainId, token)
.then((response: any) => {
console.log("response: ", response);
})
.catch((error) => {
console.error(error);
});
4 changes: 2 additions & 2 deletions src/channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ export default class Channels {
try {
const response = await fetch(
new URL(
`${domainId}/channels/${channel.id}`,
`${domainId}/${this.channelsEndpoint}/${channel.id}`,
this.channelsUrl
).toString(),
options
Expand Down Expand Up @@ -261,7 +261,7 @@ export default class Channels {
try {
const response = await fetch(
new URL(
`${domainId}/channels/${channel.id}/tags`,
`${domainId}/${this.channelsEndpoint}/${channel.id}/tags`,
this.channelsUrl
).toString(),
options
Expand Down
44 changes: 44 additions & 0 deletions src/defs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -379,3 +379,47 @@ export interface MembersPage {
offset: number;
limit: number;
}

export interface Script {
type: number;
value: string;
}

export interface Schedule {
date?: Date;
recurring_type: number;
recurring_period: number;
}

export type RuleStatus = "enabled" | "disabled" | "deleted" | "all" | "unknown";
export interface Rule {
id?: string;
name?: string;
domain?: string;
input_channel?: string;
input_topic?: string;
logic?: Script;
output_channel?: string;
output_topic?: string;
schedule?: Schedule;
status?: RuleStatus;
created_by?: string;
created_at?: Date;
updated_at?: Date;
updated_by?: string;
}

export interface RulesPageMetadata {
total?: number;
offset?: number;
limit?: number;
dir?: string;
name?: string;
input_channel?: string;
output_channel?: string;
status?: RuleStatus;
}

export interface RulesPage extends RulesPageMetadata {
rules: Rule[];
}
228 changes: 228 additions & 0 deletions src/re.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
import { Rule, RulesPage, RulesPageMetadata, Response } from "./defs";
import Errors from "./errors";

/**
* @class Rules
* Handles interactions with rules API, including creating, updating and managing rules.
*/
export default class Rules {
private readonly contentType: string;

private readonly rulesEndpoint: string;

private readonly rulesUrl: URL;

/**
* @constructor
* Initializes the Rules API client.
* @param {object} config - Configuration object.
* @param {string} config.rulesUrl - Base URL for the rules API.
*/
public constructor({ rulesUrl }: { rulesUrl: string }) {
this.rulesUrl = new URL(rulesUrl);
this.contentType = "application/json";
this.rulesEndpoint = "rules";
}

/**
* @method CreateRule - Creates a new rule
* @param {Rule} rule - Rule object with a containing details like name, input_channel, input_topic and logic.
* @param {string} domainId - The unique ID of the domain.
* @param {string} token - Authorization token.
* @returns {Promise<Rule>} rule - The created rule object.
* @throws {Error} - If the rule cannot be created.
*/
public async CreateRule(
rule: Rule,
domainId: string,
token: string
): Promise<Rule> {
const options: RequestInit = {
method: "POST",
headers: {
"Content-Type": this.contentType,
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(rule),
};
try {
const response = await fetch(
new URL(`${domainId}/${this.rulesEndpoint}`, this.rulesUrl).toString(),
options
);
if (!response.ok) {
const errorRes = await response.json();
throw Errors.HandleError(errorRes.message, response.status);
}
const newRule: Rule = await response.json();
return newRule;
} catch (error) {
throw error;
}
}

/**
* @method ViewRule - Retrieves a rule by its id.
* @param {string} ruleId - The unique ID of the rule.
* @param {string} domainId - The unique ID of the domain.
* @param {string} token - Authorization token.
* @returns {Promise<Rule>} rule - The requested rule object.
* @throws {Error} - If the rule cannot be fetched.
*/
public async ViewRule(
ruleId: string,
domainId: string,
token: string
): Promise<Rule> {
const options: RequestInit = {
method: "GET",
headers: {
"Content-Type": this.contentType,
Authorization: `Bearer ${token}`,
},
};
try {
const response = await fetch(
new URL(
`${domainId}/${this.rulesEndpoint}/${ruleId}`,
this.rulesUrl
).toString(),
options
);
if (!response.ok) {
const errorRes = await response.json();
throw Errors.HandleError(errorRes.message, response.status);
}
const rule: Rule = await response.json();
return rule;
} catch (error) {
throw error;
}
}

/**
* @method ListRules - Retrieves all rules matching the provided query parameters.
* @param {RulesPageMetadata} queryParams - Query parameters for the request.
* @param {string} domainId - The unique ID of the domain.
* @param {string} token - Authorization token.
* @returns {Promise<RulesPage>} rulesPage - A page of rules.
* @throws {Error} - If the rules cannot be fetched.
*/
public async ListRules(
queryParams: RulesPageMetadata,
domainId: string,
token: string
): Promise<RulesPage> {
const stringParams: Record<string, string> = Object.fromEntries(
Object.entries(queryParams).map(([key, value]) => [key, String(value)])
);
const options: RequestInit = {
method: "GET",
headers: {
"Content-Type": this.contentType,
Authorization: `Bearer ${token}`,
},
};
try {
const response = await fetch(
new URL(
`${domainId}/${this.rulesEndpoint}?${new URLSearchParams(
stringParams
).toString()}`,
this.rulesUrl
).toString(),
options
);
if (!response.ok) {
const errorRes = await response.json();
throw Errors.HandleError(errorRes.message, response.status);
}
const rulesPage: RulesPage = await response.json();
return rulesPage;
} catch (error) {
throw error;
}
}

/**
* @method UpdateRule - Updates an existing rule.
* @param {Rule} rule - rule object with updated properties.
* @param {string} domainId - The unique ID of the domain.
* @param {string} token - Authorization token.
* @returns {Promise<Rule>} rule - The updated rule object.
* @throws {Error} - If the rule cannot be updated.
*/
public async UpdateRule(
rule: Rule,
domainId: string,
token: string
): Promise<Rule> {
const options: RequestInit = {
method: "PUT",
headers: {
"Content-Type": this.contentType,
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(rule),
};
try {
const response = await fetch(
new URL(
`${domainId}/${this.rulesEndpoint}/${rule.id}`,
this.rulesUrl
).toString(),
options
);
if (!response.ok) {
const errorRes = await response.json();
throw Errors.HandleError(errorRes.message, response.status);
}
const updatedRule: Rule = await response.json();
return updatedRule;
} catch (error) {
throw error;
}
}

/**
* @method DeleteRule - Deletes a rule.
* @param {string} ruleId - The unique ID of the rule.
* @param {string} domainId - The unique ID of the domain.
* @param {string} token - Authorization token.
* @returns {Promise<Response>} response - A promise that resolves when the rule is successfully deleted.
* @throws {Error} - If the rule status cannot be updated.
*/
public async DeleteRule(
ruleId: string,
domainId: string,
token: string
): Promise<Response> {
const options = {
method: "PUT",
headers: {
"Content-Type": this.contentType,
Authorization: `Bearer ${token}`,
},
};
try {
const response = await fetch(
new URL(
`${domainId}/${this.rulesEndpoint}/${ruleId}/delete`,
this.rulesUrl
).toString(),
options
);
if (!response.ok) {
const errorRes = await response.json();
throw Errors.HandleError(errorRes.message, response.status);
}
const statusResponse: Response = {
status: response.status,
message: "Rule status updated successfully",
};
return statusResponse;
} catch (error) {
throw error;
}
}
}
Loading

0 comments on commit 893a8f6

Please sign in to comment.