Skip to content
This repository was archived by the owner on Sep 19, 2024. It is now read-only.

Commit 42067c6

Browse files
authored
feat!: clean up resources
2 parents c6618a7 + cea96d5 commit 42067c6

21 files changed

+337
-111
lines changed

README.md

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -37,24 +37,29 @@ This plugin gives you a new and isolated database for your preview deployments i
3737
#### Inputs
3838

3939
```yaml
40-
- name: databaseEnvVar
41-
required: false
42-
description: Database environment variable name
43-
default: "DATABASE_URL"
44-
4540
- name: databaseCreateCommand
4641
required: false
47-
description: Command used to generate the instant database
42+
description: Command used to create the preview database
4843
default: "snaplet db create --git --latest"
4944

45+
- name: databaseDeleteCommand
46+
required: false
47+
description: Command used to delete the preview database
48+
default: "snaplet db delete --git"
49+
5050
- name: databaseUrlCommand
5151
required: false
52-
description: Command used to get the instant database url
52+
description: Command used to get the preview database url
5353
default: "snaplet db url --git"
5454

55+
- name: databaseUrlEnvKey
56+
required: false
57+
description: Preview database environment variable key
58+
default: "DATABASE_URL"
59+
5560
- name: reset
5661
required: false
57-
description: Reset the database state on each commit
62+
description: Reset the preview database state on each commit
5863
default: false
5964
```
6065
@@ -78,10 +83,15 @@ This plugin gives you a new and isolated database for your preview deployments i
7883

7984
#### Required Environment variables
8085

81-
```
82-
NETLIFY_ACCESS_TOKEN=// API Access token found in Netlify user settings.
83-
SNAPLET_ACCESS_TOKEN=// CLI Access token found in Snaplet UI
84-
SNAPLET_PROJECT_ID=// Project ID found in Snaplet project settings.
86+
```bash
87+
# Personal Access Token with "repo" scope, found in GitHub user settings
88+
GITHUB_ACCESS_TOKEN=
89+
# API Access token found in Netlify user settings
90+
NETLIFY_ACCESS_TOKEN=
91+
# CLI Access token found in Snaplet UI
92+
SNAPLET_ACCESS_TOKEN=
93+
# Project ID found in Snaplet project settings
94+
SNAPLET_PROJECT_ID=
8595
```
8696

8797
## How it works

jsconfig.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"compilerOptions": {
3+
"checkJs": true
4+
}
5+
}

manifest.yml

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,27 @@
11
name: snaplet-netlify-plugin-preview-db
22

33
inputs:
4-
- name: databaseEnvVar
5-
required: false
6-
description: Database environment variable name
7-
default: "DATABASE_URL"
8-
94
- name: databaseCreateCommand
105
required: false
11-
description: Command used to generate the instant database
6+
description: Command used to create the preview database
127
default: "snaplet db create --git --latest"
138

9+
- name: databaseDeleteCommand
10+
required: false
11+
description: Command used to delete the preview database
12+
default: "snaplet db delete --git"
13+
1414
- name: databaseUrlCommand
1515
required: false
16-
description: Command used to get the instant database url
16+
description: Command used to get the preview database url
1717
default: "snaplet db url --git"
1818

19+
- name: databaseUrlEnvKey
20+
required: false
21+
description: Preview database environment variable key
22+
default: "DATABASE_URL"
23+
1924
- name: reset
2025
required: false
21-
description: Reset the database state on each commit
26+
description: Reset the preview database state on each commit
2227
default: false

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@snaplet/netlify-preview-database-plugin",
3-
"version": "1.1.0",
3+
"version": "2.0.0",
44
"type": "module",
55
"main": "src/index.js",
66
"license": "MIT",

src/getPreviewDatabaseUrl.js

Lines changed: 0 additions & 7 deletions
This file was deleted.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { github } from "./github.js";
2+
3+
/**
4+
* @param {{ commitRef: string }} options
5+
*/
6+
export async function getAssociatedPullRequests(options) {
7+
/** @type {{ head: { ref: string }}[]} */
8+
const associatedPullRequests = await github(`commits/${options.commitRef}/pulls`);
9+
10+
return associatedPullRequests;
11+
}

src/github/github.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import fetch from "node-fetch";
2+
3+
const [OWNER, REPOSITORY] = new URL(process.env.REPOSITORY_URL).pathname.slice(1).split("/");
4+
5+
/**
6+
* @template T
7+
* @param {string} path
8+
* @returns {Promise<T>}
9+
*/
10+
export async function github(path, options) {
11+
const response = await fetch(`https://api.github.com/repos/${OWNER}/${REPOSITORY}/${path}`, {
12+
headers: {
13+
Accept: "application/vnd.github+json",
14+
Authorization: `Bearer ${process.env.GITHUB_ACCESS_TOKEN}`,
15+
"Content-Type": "application/json",
16+
},
17+
...options
18+
});
19+
20+
if (!response.ok) {
21+
throw new Error(`GitHub API error: ${response.status} ${response.statusText}`);
22+
}
23+
24+
// @ts-ignore
25+
return await response.json();
26+
}

src/handleDeployPreview.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { createPreviewDatabase } from "./snaplet/previewDatabase/createPreviewDatabase.js"
2+
import { installSnapletCLI } from "./snaplet/installSnapletCLI.js";
3+
import { setEnvironmentVariable } from "./netlify/environmentVariable/setEnvironmentVariable.js";
4+
5+
/**
6+
* @param {{
7+
* utils: { run: { command: (cmd: string, options: Record<string, any>) => { stdout: string } } },
8+
* inputs: { databaseCreateCommand: string, databaseUrlCommand: string, databaseUrlEnvKey: string, reset: boolean }
9+
* }} config
10+
*/
11+
export async function handleDeployPreview({
12+
utils: { run },
13+
inputs: {
14+
databaseCreateCommand,
15+
databaseUrlCommand,
16+
databaseUrlEnvKey,
17+
reset,
18+
},
19+
}) {
20+
await installSnapletCLI({ run });
21+
22+
const databaseUrl = await createPreviewDatabase({ run }, {
23+
databaseCreateCommand,
24+
databaseUrlCommand,
25+
reset,
26+
});
27+
28+
await setEnvironmentVariable({
29+
siteId: process.env.SITE_ID,
30+
branch: process.env.HEAD,
31+
key: databaseUrlEnvKey,
32+
value: databaseUrl,
33+
});
34+
};

src/handleDeployProduction.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { installSnapletCLI } from "./snaplet/installSnapletCLI.js";
2+
import { getAssociatedPullRequests } from "./github/getAssociatedPullRequests.js";
3+
import { deletePreviewDatabase } from "./snaplet/previewDatabase/deletePreviewDatabase.js";
4+
import { deleteEnvironmentVariable } from "./netlify/environmentVariable/deleteEnvironmentVariable.js";
5+
6+
/**
7+
* @param {{
8+
* utils: { run: { command: (cmd: string, options: Record<string, any>) => { stdout: string } } },
9+
* inputs: { databaseDeleteCommand: string, databaseUrlCommand: string, databaseUrlEnvKey: string }
10+
* }} config
11+
*/
12+
export async function handleDeployProduction({
13+
utils: { run },
14+
inputs: {
15+
databaseDeleteCommand,
16+
databaseUrlCommand,
17+
databaseUrlEnvKey,
18+
},
19+
}) {
20+
const associatedPullRequests = await getAssociatedPullRequests({ commitRef: process.env.COMMIT_REF });
21+
22+
if (associatedPullRequests.length > 0) {
23+
await installSnapletCLI({ run });
24+
25+
await Promise.all(associatedPullRequests.map(async (pullRequest) => {
26+
const branch = pullRequest.head.ref;
27+
28+
await Promise.all([
29+
deleteEnvironmentVariable({ branch, key: databaseUrlEnvKey, siteId: process.env.SITE_ID }),
30+
deletePreviewDatabase({ run }, { branch, databaseDeleteCommand, databaseUrlCommand }),
31+
]);
32+
}));
33+
}
34+
}

src/index.js

Lines changed: 23 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,26 @@
1-
import { createPreviewDatabase } from "./createPreviewDatabase.js"
2-
import { installSnapletCLI } from "./installSnapletCLI.js";
3-
import { setEnvironmentVariable } from "./setEnvironmentVariable.js";
1+
import { handleDeployPreview } from "./handleDeployPreview.js";
2+
import { handleDeployProduction } from "./handleDeployProduction.js";
43

5-
export async function onPreBuild({
6-
utils: { run },
7-
constants,
8-
netlifyConfig,
9-
inputs: {
10-
databaseEnvVar,
11-
databaseCreateCommand,
12-
databaseUrlCommand,
13-
reset,
14-
},
15-
}) {
16-
if (process.env.CONTEXT === "deploy-preview") {
17-
await installSnapletCLI({ run });
18-
19-
const databaseUrl = await createPreviewDatabase({ run }, {
20-
databaseCreateCommand,
21-
databaseUrlCommand,
22-
reset,
23-
});
24-
25-
await setEnvironmentVariable({
26-
siteId: constants.SITE_ID,
27-
branch: netlifyConfig.build.environment.BRANCH,
28-
key: databaseEnvVar,
29-
value: databaseUrl,
30-
});
4+
/**
5+
* @param {{
6+
* utils: { run: { command: (cmd: string, options: Record<string, any>) => { stdout: string } } },
7+
* inputs: { databaseCreateCommand: string, databaseDeleteCommand: string, databaseUrlCommand: string, databaseUrlEnvKey: string, reset: boolean }
8+
* }} config
9+
*/
10+
export async function onPreBuild(config) {
11+
switch (process.env.CONTEXT) {
12+
case "deploy-preview":
13+
await handleDeployPreview(config);
14+
break;
15+
case "production":
16+
try {
17+
await handleDeployProduction(config);
18+
} catch (e) {
19+
// We don't want the production build to fail because of resources clean up
20+
console.error(`Failed to clean up resources for this commit`);
21+
console.error(e);
22+
}
23+
break;
24+
default:
3125
}
3226
};

0 commit comments

Comments
 (0)