Back to packages list

Vals using axios

Description from the NPM package:
Promise based HTTP client for the browser and node.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import axios from "npm:axios";
import * as cheerio from "npm:cheerio";
export async function extractOpenGraphTags(request: Request) {
try {
const body = await request.json();
const url = body.url;
if (url) {
const response = await axios.get(url);
const html = response.data;
const $ = cheerio.load(html);
const openGraphTags = [];
$("meta[property^='og:']").each((i, el) => {
const property = $(el).attr("property");
const content = $(el).attr("content");
if (property && content) {
openGraphTags.push({ property, content });
}
});
return Response.json(openGraphTags);
} else {
return Response.json({ message: "URL not found" }, {
status: 400,
});
}
} catch (error) {
console.error("Error:", error);
return Response.json({ message: "The body of this request was not JSON-encoded." }, {
status: 400,
});
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=41";
import axios from "npm:axios";
import formData from "npm:form-data";
export const telegramSendMessage = async (botToken: string, options: {
chat_id: string | number;
text: string;
message_thread_id?: number;
parse_mode?: string;
entities?: any[];
disable_web_page_preview?: boolean;
disable_notification?: boolean;
protect_content?: boolean;
reply_to_message_id?: number;
allow_sending_without_reply?: boolean;
reply_markup?: any[];
}) =>
fetchJSON(
`https://api.telegram.org/bot${botToken}/sendMessage`,
{
method: "POST",
body: JSON.stringify({ ...options }),
},
);
export async function telegramSendAudioMessage(chatId: string, audioData: Uint8Array, botToken: string): Promise<void> {
const url = `https://api.telegram.org/bot${botToken}/sendAudio`;
// Assuming FormData is available or correctly polyfilled
let data = new FormData();
data.append("chat_id", chatId);
// Directly use the Uint8Array with Blob constructor
data.append("audio", new Blob([audioData], { type: "audio/mpeg" }), "feedback.mpga");
try {
// Replace axios with Deno's fetch API, adapted for your setup
const response = await fetch(url, {
method: "POST",
body: data, // FormData instance directly as the body
// Headers are set automatically by the browser, so they're omitted here
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error sending audio message:", error.message);
}
}

Zoho Desk API

A set of method to easily grab information on Zoho Desk! Official API Documentation is here.

Notes

It's needed to create a Self Client Application as described here to use this val. You also need to find your org id (under Setup > API > Zoho Service Communication (ZSC) Key > OrgId).

Methods

As of today here is the methods in this val:

  • refreshAccessToken to generate a valid Access Token based on client id, client secret and a refresh token. Follow the step here to register a client and generate a refresh token.
  • notAssignedTickets to extract the currently not assigned tickets in a specified department
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import axios from "npm:axios";
export const refreshAccessToken = async (
clientId: string,
clientSecret: string,
refreshToken: string,
): Promise<string> => {
const responseDesk = await axios.post(
`https://accounts.zoho.com/oauth/v2/token`,
{}, // data is empty
{
params: {
client_id: clientId,
client_secret: clientSecret,
refresh_token: refreshToken,
grant_type: "refresh_token",
},
},
);
return responseDesk.data.access_token;
};
type Ticket = any;
export const notAssignedTickets = async (
accessToken: string,
orgId: string,
departmentId: string,
): Promise<{ data: Ticket[] }> => {
const responseDesk = await axios.get(
`https://desk.zoho.com/api/v1/tickets`,
{
params: {
limit: "100",
departmentIds: departmentId,
assignee: "Unassigned",
status: "${ONHOLD},${OPEN}",
},
headers: {
"Authorization": `Zoho-oauthtoken ${accessToken}`,
"orgId": orgId,
},
},
);
if (responseDesk.status === 422) {
// no data, return empty array
return {
data: [],
};
}
return responseDesk.data;
};
Runs every 15 min
Fork
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { rule } from "https://esm.town/v/cescyang_service/rule";
import { email } from "https://esm.town/v/std/email?v=9";
import { fetch } from "https://esm.town/v/std/fetch";
export async function checkAndroidBingApps() {
const { default: axios } = await import("npm:axios");
const url =
"https://sapphire.api.microsoftapp.net/config/api/v1/get?setmkt=en-us&setplatform=android&setchannel=production&settenant=sapphire-bing";
try {
const response = await fetch(url, {
method: "GET",
});
const data = await response.json();
console.log(data);
const validateData = rule(data);
if (!validateData?.validate) {
email({
text: "ios config missing\n" + validateData.difference,
subject: "ios config missing\n" + validateData.difference,
});
}
}
catch (error) {
console.error("Error:", error);
return "Error occurred while accessing the URL , " + error.message;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
export const script_6sbfbg98wajm0b51pjunnu2pwj8nbi98 = (async function() {
const rosters = {
"Zack": ["PHI", "WSH", "IND", "TB", "LAR", "TEN", "HOU"],
"Joel": ["BUF", "BAL", "NE", "NYG", "CHI"],
"Ric": ["KC", "CIN", "MIA", "GB", "LV"],
"Joey": ["DAL", "LAC", "SEA", "NO", "ARI"],
"Will": ["SF", "MIN", "CLE", "PIT", "CAR"],
"Max": ["DET", "NYJ", "JAX", "ATL", "DEN"],
};
const findRoster = (team: string) => {
for (const roster in rosters) {
if (rosters[roster].includes(team)) {
return roster;
}
}
console.log("ERROR: no roster found for " + team);
};
const getStandings = () => {
let standings = {};
for (const roster in rosters) {
standings[roster] = rosters[roster].map((team) => ({
team: team,
wins: 0,
obo: 0,
dbo: 0,
bonuses: [],
}));
}
return standings;
};
const main = async () => {
const { default: axios } = await import("npm:axios");
const getScores = async (week: number) => {
const { data } = await axios.get(
"http://site.api.espn.com/apis/site/v2/sports/football/nfl/scoreboard",
);
let standings = getStandings();
console.log(standings);
let games = [];
for (let event of data.events) {
if (event.week.number === week) {
const homeTeam = event.competitions[0].competitors[0].team.abbreviation;
const awayTeam = event.competitions[0].competitors[1].team.abbreviation;
games.push({
homeTeam: homeTeam,
homeScore: parseInt(event.competitions[0].competitors[0].score),
homeRoster: findRoster(homeTeam),
awayTeam: awayTeam,
awayScore: parseInt(event.competitions[0].competitors[1].score),
awayRoster: findRoster(awayTeam),
});
}
}
return games;
};
return await getScores(1);
};
return await main();
})();

Get All Rows of a Database in Notion

Reference: Query a Database

How to get an access token: https://developers.notion.com/reference/create-a-token

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
export const getAllNotionDbRows = async (databaseId, notionAccessToken) => {
if (!databaseId) {
console.error("No Database ID Provided");
return null;
}
if (!notionAccessToken) {
console.warn("Notion Access Token is invalid");
return null;
}
const { default: axios } = await import("npm:axios");
const getNotionDbContent = async (start_cursor = undefined) => {
return await axios({
method: "POST",
url: `https://api.notion.com/v1/databases/${databaseId}/query`,
headers: {
Authorization: `Bearer ${notionAccessToken}`,
"Notion-Version": "2022-06-28",
"Content-Type": "application/json",
},
data: {
start_cursor,
},
});
};
let result = await getNotionDbContent();
let items = result.data.results;
while (result?.data?.has_more) {
result = await getNotionDbContent(result.data.next_cursor);
items = items.concat(result?.data?.results);
}
const { length } = items;
console.log(
length
? `Successfully fetched ${length} row${length === 1 ? "" : "s"}`
: "No rows found",
);
return items;
};

Get All Videos in a Youtube Playlist using the Youtube Data API v3

Reference: https://developers.google.com/youtube/v3/docs/playlistItems/list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
export async function getAllVideosInYoutubePlaylist(playlistId, apiKey) {
const { default: axios } = await import("npm:axios");
if (!playlistId) {
console.error("No Playlist ID Provided");
return null;
}
if (!apiKey) {
console.warn("API Key is Invalid");
return null;
}
const getPlaylistVideos = async (pageToken = "") => {
return await axios({
method: "GET",
url: "https://www.googleapis.com/youtube/v3/playlistItems",
params: {
key: apiKey,
part: "contentDetails,id,snippet",
playlistId,
maxResults: 50,
pageToken,
},
});
};
let result = await getPlaylistVideos();
let items = result.data.items;
while (result?.data?.nextPageToken) {
result = await getPlaylistVideos(result.data.nextPageToken);
if (result?.data?.items) {
items = items.concat(result.data.items);
}
}
const { length } = items;
console.log(
length
? `Successfully fetched ${length} video${length === 1 ? "" : "s"}`
: "No videos found",
);
return items;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type Config = {
token: string;
};
export async function createTibberApi(config: Config) {
const { default: axios } = await import("https://esm.sh/axios");
const client = axios.create({
baseURL: "https://api.tibber.com/v1-beta",
method: "POST",
headers: {
authorization: `Bearer ${config.token}`,
},
});
const query = async <R>(q: string): Promise<R> => {
const { data } = await client.post("/gql", { query: q });
return data;
};
return { query };
}
Runs every 15 min
Fork
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { rule } from "https://esm.town/v/cescyang_service/rule";
import { email } from "https://esm.town/v/std/email?v=9";
import { fetch } from "https://esm.town/v/std/fetch";
export async function checkAndroidBingApps() {
const { default: axios } = await import("npm:axios");
const url =
"https://sapphire.api.microsoftapp.net/config/api/v1/get?setmkt=en-us&setplatform=android&setchannel=production&settenant=sapphire-bing";
try {
const response = await fetch(url, {
method: "GET",
});
const data = await response.json();
console.log(data);
const validateData = rule(data);
if (!validateData?.validate) {
email({
text: "android config missing\n" + validateData.difference,
subject: "android config missing\n" + validateData.difference,
});
}
}
catch (error) {
console.error("Error:", error);
return "Error occurred while accessing the URL , " + error.message;
}
}
1
2
3
4
5
export const axiosEx = (async () => {
const { default: axios } = await import("https://esm.sh/axios");
let r = await axios.get("https://api.github.com/users/stevekrouse/following");
return JSON.stringify(r);
})();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
export async function test() {
const { default: axios } = await import("npm:axios");
const url = "http://207.244.232.58:8011/api/login";
const message = "testing";
const loginInfo = {
username: "HAZAH",
password: "HAZAHisOP1!",
};
try {
const response = await axios.post(url, loginInfo);
const data = response.json();
console.log("test");
console.log(data);
return true;
}
catch (error) {
console.log(error);
return false;
}
}
Runs every 30 min
Fork
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { fetch } from "https://esm.town/v/std/fetch";
export async function checkPollingStatus() {
const { default: axios } = await import("npm:axios");
const tasUrl =
"https://default.exp-tas.com/exptas9/a5766fee-9478-488b-9fc0-64d1ad72c290-IcePrime_MSNApp/api/v1/tas";
const urls = [
"https://sapphire-assignment-api-westus2-01-01.azurewebsites.net/api/VariantAssignment/checkPollingStatus",
"https://sapphire-assignment-api-eastus2-02-01.azurewebsites.net/api/VariantAssignment/checkPollingStatus",
"https://sapphire-assignment-api-japaneast-01-01.azurewebsites.net/api/VariantAssignment/checkPollingStatus",
"https://sapphire-assignment-api-koreacenter-01-01.azurewebsites.net/api/VariantAssignment/checkPollingStatus",
"https://sapphire-assignment-api-northeurope-01-01.azurewebsites.net/api/VariantAssignment/checkPollingStatus",
"https://sapphire-assignment-api-westeurope-01-01.azurewebsites.net/api/VariantAssignment/checkPollingStatus",
"https://sapphire-assignment-api-westus2-02-01.azurewebsites.net/api/VariantAssignment/checkPollingStatus",
];
const results = [];
const tasResponse = await fetch(tasUrl, {
method: "GET",
});
let tasRstStr = "";
if (tasResponse.ok) {
tasRstStr = await tasResponse.text();
}
for (const url of urls) {
try {
const response = await fetch(url, {
method: "GET",
});
if (response.ok) {
const data = await response.text();
const status = data.includes("success") ? "Normal" : "Failed";
results.push({ url, status, data });
}
else {
results.push({ url, status: "Failed" });
}
}
catch (error) {
results.push({ url, status: "Error" });
}
}
const emailContent = results.map((result) =>
`${result.url}: ${result.status}: ${result.data} `
);
emailContent.push(tasRstStr);
if (results.some((result) => result.status === "Failed")) {
console.email({
"[PollingFailed]": "HealthCheck Failed",
"Results": emailContent,
}, "Subject line");
}
// else {
// console.email({
// "[PollingSuccess]": "HealthCheck Success",
// "Results": emailContent,
// }, "Subject line");
// }
}
1
2
3
4
5
export const axiosTest = (async () => {
const { default: axios } = await import("npm:axios");
const res = await axios.get("https://jsonplaceholder.typicode.com/todos/1");
return res;
})();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
export async function untitled_magentaBee() {
const { default: axios } = await import("npm:axios");
const url =
"https://microsoft.webhook.office.com/webhookb2/c092e225-69b9-4c55-8596-6080dd20a0c7@72f988bf-86f1-41af-91ab-2d7cd011db47/IncomingWebhook/c66ca2ccd2e841a08d659cfc06004324/76bcdcb1-ab16-4d46-96d0-8c219165d40a";
const message = "testing";
const card = {
type: "message",
attachments: [
{
contentType: "application/vnd.microsoft.card.adaptive",
contentUrl: null,
content: {
$schema: "http://adaptivecards.io/schemas/adaptive-card.json",
type: "AdaptiveCard",
version: "1.2",
body: [
{
type: "TextBlock",
text: message,
},
],
},
},
],
};
try {
const response = await axios.post(url, card);
// const data = response.json();
console.log(response);
return true;
}
catch (error) {
console.log(error);
return false;
}
}
Runs every 15 min
Fork
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { fetch } from "https://esm.town/v/std/fetch";
import { rule } from "https://esm.town/v/cescyang/rule";
export async function checkAndroidBingApps() {
const { default: axios } = await import("npm:axios");
const url =
"https://sapphire.api.microsoftapp.net/config/api/v1/get?setmkt=en-us&setplatform=android&setchannel=production&settenant=sapphire-bing";
try {
const response = await fetch(url, {
method: "GET",
});
const data = await response.json();
console.log(data);
const validateData = rule(data);
return validateData.validate ? console.log("normal") : console.email({
FAILED: "android config missing\n" + validateData.difference,
}, "Subject line");
}
catch (error) {
console.error("Error:", error);
return "Error occurred while accessing the URL , " + error.message;
}
}