forked from Faolain/railway-pr-delete
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
103 lines (88 loc) · 3.1 KB
/
index.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
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
const core = require('@actions/core');
const { request, gql, GraphQLClient } = require('graphql-request')
// Railway Required Inputs
const RAILWAY_API_TOKEN = core.getInput('RAILWAY_API_TOKEN');
const PROJECT_ID = core.getInput('PROJECT_ID');
const DEST_ENV_NAME = core.getInput('DEST_ENV_NAME');
const ENDPOINT = 'https://backboard.railway.app/graphql/v2';
async function railwayGraphQLRequest(query, variables) {
const client = new GraphQLClient(ENDPOINT, {
headers: {
Authorization: `Bearer ${RAILWAY_API_TOKEN}`,
},
})
try {
return await client.request({ document: query, variables })
} catch (error) {
core.setFailed(`Action failed with error: ${error}`);
}
}
async function getEnvironmentId() {
let query =
`query environments($projectId: String!) {
environments(projectId: $projectId) {
edges {
node {
id
name
serviceInstances {
edges {
node {
domains {
serviceDomains {
domain
}
}
serviceId
startCommand
}
}
}
}
}
}
}`
const variables = {
"projectId": PROJECT_ID,
}
return await railwayGraphQLRequest(query, variables)
}
async function checkIfEnvironmentExists() {
let response = await getEnvironmentId();
const filteredEdges = response.environments.edges.filter((edge) => edge.node.name === DEST_ENV_NAME);
return filteredEdges.length == 1 ? { environmentId: filteredEdges[0].node.id } : null;
}
async function deleteEnvironment(environmentId) {
try {
let query = gql`
mutation environmentDelete($id: String!) {
environmentDelete(id: $id)
}
`
let variables = {
"id": environmentId,
}
return await railwayGraphQLRequest(query, variables)
} catch (error) {
core.setFailed(`Action failed with error: ${error}`);
}
}
async function run() {
try {
const environmentIfExists = await checkIfEnvironmentExists();
if (!environmentIfExists) {
throw new Error('Environment does not exist. It may have already been deleted or it was never created');
}
const envrionmentDeleted = await deleteEnvironment(environmentIfExists?.environmentId);
if (envrionmentDeleted) {
console.log(`Environment ${DEST_ENV_NAME} deleted successfully.`);
} else {
throw new Error(`Environment ${DEST_ENV_NAME} could not be deleted.`);
}
} catch (error) {
console.log(error)
// Handle the error, e.g., fail the action
core.setFailed('API calls failed');
}
}
run();