Skip to content

Commit c8dba92

Browse files
authored
Merge pull request #378 from Chrisyhjiang/sveltekit
Sveltekit sample
2 parents 129b421 + cc99dbe commit c8dba92

32 files changed

+738
-32
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,7 @@ node_modules/
55
/result
66

77

8-
.log
8+
*.log
9+
*.txt
910
.gitignore
11+
*-lock.json

README.md

Lines changed: 44 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,87 +1,102 @@
11
[![Go package](https://github.com/defang-io/defang/actions/workflows/go.yml/badge.svg?branch=main)](https://github.com/defang-io/defang/actions/workflows/go.yml)
22

33
# Defang
4+
45
Defang is a radically simpler way for developers to create, deploy, and manage cloud applications.
56

67
This repo includes:
7-
* Public releases of the Defang CLI; [click here](https://github.com/defang-io/defang/releases/latest/) for the latest version
8-
* Samples in Golang, Python, and Node.js that show how to accomplish various tasks and deploy them to the DOP using a Docker Compose file using the Defang CLI.
9-
* Samples that show how to deploy an app using the [Defang Pulumi Provider](https://github.com/defang-io/pulumi-defang).
8+
9+
- Public releases of the Defang CLI; [click here](https://github.com/defang-io/defang/releases/latest/) for the latest version
10+
- Samples in Golang, Python, and Node.js that show how to accomplish various tasks and deploy them to the DOP using a Docker Compose file using the Defang CLI.
11+
- Samples that show how to deploy an app using the [Defang Pulumi Provider](https://github.com/defang-io/pulumi-defang).
1012

1113
## Getting started
12-
* Read our [Getting Started](https://docs.defang.io/docs/getting-started) page
13-
* Follow the installation instructions from the [Installing](https://docs.defang.io/docs/getting-started/installing) page
14-
* Take a look at our [Samples folder](https://github.com/defang-io/defang/tree/main/samples) for example projects in various programming languages.
15-
* Try the AI integration by running `defang generate`
16-
* Start your new service with `defang compose up`
14+
15+
- Read our [Getting Started](https://docs.defang.io/docs/getting-started) page
16+
- Follow the installation instructions from the [Installing](https://docs.defang.io/docs/getting-started/installing) page
17+
- Take a look at our [Samples folder](https://github.com/defang-io/defang/tree/main/samples) for example projects in various programming languages.
18+
- Try the AI integration by running `defang generate`
19+
- Start your new service with `defang compose up`
1720

1821
## Installing
22+
1923
Install the Defang CLI from one of the following sources:
20-
* Using the [Homebrew](https://brew.sh) package manager [defang-io/defang tap](https://github.com/defang-io/homebrew-defang):
24+
25+
- Using the [Homebrew](https://brew.sh) package manager [defang-io/defang tap](https://github.com/defang-io/homebrew-defang):
2126
```
2227
brew install defang-io/defang/defang
2328
```
24-
* Using a shell script:
29+
- Using a shell script:
2530
```
2631
. <(curl -Ls https://s.defang.io/install)
2732
```
28-
* Using [Go](https://go.dev):
33+
- Using [Go](https://go.dev):
2934
```
3035
go install github.com/defang-io/defang/src/cmd/cli@latest
3136
```
32-
* Using the [Nix package manager](https://nixos.org):
33-
* with Nix-Env:
37+
- Using the [Nix package manager](https://nixos.org):
38+
- with Nix-Env:
3439
```
3540
nix-env -if https://github.com/defang-io/defang/archive/main.tar.gz
3641
```
37-
* or with Flakes:
42+
- or with Flakes:
3843
```
3944
nix profile install github:defang-io/defang#defang-bin --refresh
4045
```
41-
* Download the [latest binary](https://github.com/defang-io/defang/releases/latest/) of the Defang CLI. For this beta, MacOS users will have to explicitly allow running of downloaded programs in the OS security settings.
46+
- Download the [latest binary](https://github.com/defang-io/defang/releases/latest/) of the Defang CLI. For this beta, MacOS users will have to explicitly allow running of downloaded programs in the OS security settings.
4247
4348
## Support
44-
* File any issues [right here on GitHub](https://github.com/defang-io/defang/issues)
49+
50+
- File any issues [right here on GitHub](https://github.com/defang-io/defang/issues)
4551
4652
## Command completion
53+
4754
The Defang CLI supports command completion for Bash, Zsh, Fish, and Powershell. To get the shell script for command completion, run the following command:
55+
4856
```
4957
defang completion [bash|zsh|fish|powershell]
5058
```
5159
5260
If you're using Bash, you can add the following to your `~/.bashrc` file:
61+
5362
```
5463
source <(defang completion bash)
5564
```
5665
5766
If you're using Zsh, you can add the following to your `~/.zshrc` file:
67+
5868
```
5969
source <(defang completion zsh)
6070
```
71+
6172
or pipe the output to a file called `_defang` in the directory with the completions.
6273
6374
If you're using Fish, you can add the following to your `~/.config/fish/config.fish` file:
75+
6476
```
6577
defang completion fish | source
6678
```
6779
6880
If you're using Powershell, you can add the following to your `$HOME\Documents\PowerShell\Microsoft.PowerShell_profile.ps1` file:
81+
6982
```
7083
Invoke-Expression -Command (defang completion powershell | Out-String)
7184
```
7285
7386
## Environment Variables
87+
7488
The Defang CLI recognizes the following environment variables:
75-
* `COMPOSE_PROJECT_NAME` - The name of the project to use; overrides the name in the `compose.yaml` file
76-
* `DEFANG_ACCESS_TOKEN` - The access token to use for authentication; if not specified, uses token from `defang login`
77-
* `DEFANG_CD_BUCKET` - The S3 bucket to use for the BYOC CD pipeline; defaults to `defang-cd-bucket-…`
78-
* `DEFANG_CD_IMAGE` - The image to use for the Continuous Deployment (CD) pipeline; defaults to `public.ecr.aws/defang-io/cd:public-beta`
79-
* `DEFANG_DEBUG` - set this to `1` or `true` to enable debug logging
80-
* `DEFANG_DISABLE_ANALYTICS` - If set to `true`, disables sending analytics to Defang; defaults to `false`
81-
* `DEFANG_FABRIC` - The address of the Defang Fabric to use; defaults to `fabric-prod1.defang.dev`
82-
* `DEFANG_HIDE_HINTS` - If set to `true`, hides hints in the CLI output; defaults to `false`
83-
* `DEFANG_HIDE_UPDATE` - If set to `true`, hides the update notification; defaults to `false`
84-
* `DEFANG_PROVIDER` - The name of the cloud provider to use, `auto` (default), `aws`, or `defang`
85-
* `NO_COLOR` - If set to any value, disables color output; by default, color output is enabled depending on the terminal
86-
* `TZ` - The timezone to use for log timestamps: an IANA TZ name like `UTC` or `Europe/Amsterdam`; defaults to `Local`
87-
* `XDG_STATE_HOME` - The directory to use for storing state; defaults to `~/.local/state`
89+
90+
- `COMPOSE_PROJECT_NAME` - The name of the project to use; overrides the name in the `compose.yaml` file
91+
- `DEFANG_ACCESS_TOKEN` - The access token to use for authentication; if not specified, uses token from `defang login`
92+
- `DEFANG_CD_BUCKET` - The S3 bucket to use for the BYOC CD pipeline; defaults to `defang-cd-bucket-…`
93+
- `DEFANG_CD_IMAGE` - The image to use for the Continuous Deployment (CD) pipeline; defaults to `public.ecr.aws/defang-io/cd:public-beta`
94+
- `DEFANG_DEBUG` - set this to `1` or `true` to enable debug logging
95+
- `DEFANG_DISABLE_ANALYTICS` - If set to `true`, disables sending analytics to Defang; defaults to `false`
96+
- `DEFANG_FABRIC` - The address of the Defang Fabric to use; defaults to `fabric-prod1.defang.dev`
97+
- `DEFANG_HIDE_HINTS` - If set to `true`, hides hints in the CLI output; defaults to `false`
98+
- `DEFANG_HIDE_UPDATE` - If set to `true`, hides the update notification; defaults to `false`
99+
- `DEFANG_PROVIDER` - The name of the cloud provider to use, `auto` (default), `aws`, or `defang`
100+
- `NO_COLOR` - If set to any value, disables color output; by default, color output is enabled depending on the terminal
101+
- `TZ` - The timezone to use for log timestamps: an IANA TZ name like `UTC` or `Europe/Amsterdam`; defaults to `Local`
102+
- `XDG_STATE_HOME` - The directory to use for storing state; defaults to `~/.local/state`
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Dockerfile for Svelte frontend and Node.js backend
2+
3+
# Stage 1: Build Svelte frontend
4+
FROM node:16-alpine as frontend
5+
6+
WORKDIR /frontend
7+
8+
# Copy frontend source code
9+
COPY frontend/package*.json ./
10+
COPY frontend/ ./
11+
12+
# Install dependencies and build the frontend
13+
RUN npm install --legacy-peer-deps && npm run build
14+
15+
# Stage 2: Build Node.js backend
16+
FROM node:16-alpine as backend
17+
18+
WORKDIR /app
19+
20+
# Copy backend source code
21+
COPY backend/package*.json ./
22+
COPY backend/ ./
23+
24+
# Install dependencies
25+
RUN npm install
26+
27+
# Copy the built Svelte files
28+
COPY --from=frontend /frontend/build ./public
29+
30+
# Copy the backend source code
31+
COPY backend/ .
32+
33+
# Expose the application on port 3001
34+
EXPOSE 3001
35+
36+
# Command to run the backend
37+
CMD ["node", "server.js"]
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Svelte, Node.js, and MySQL
2+
3+
This sample project demonstrates how to deploy a full-stack application using Svelte for the frontend, Node.js for the backend, and MySQL for the database. The project uses Docker to containerize the services, making it easy to run in both development and production environments.
4+
5+
## NOTE
6+
7+
This sample showcases how you could deploy a full-stack application with Defang and Svelte and NodeJS. However, it deploys mysql db as a defang service. Defang [services](https://12factor.net/processes) are ephemeral and should not be used to run stateful workloads in production as they will be reset on every deployment. For production use cases you should use a managed database like RDS, Aiven, or others. In the future, Defang will help you provision and connect to managed databases.
8+
9+
## Essential Setup Files
10+
11+
1. Download [Defang CLI] (https://github.com/defang-io/defang)
12+
2. (optional) If you are using [Defang BYOC] (https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) authenticated your AWS account.
13+
3. (optional for local development) [Docker CLI] (https://docs.docker.com/engine/install/)
14+
15+
## Prerequisite
16+
17+
1. Download [Defang CLI] (https://github.com/defang-io/defang)
18+
2. (optional) If you are using [Defang BYOC](https://docs.defang.io/docs/concepts/defang-byoc) make sure you have properly
19+
3. [Docker CLI] (https://docs.docker.com/engine/install/)
20+
4. [NodeJS] (https://nodejs.org/en/download/package-manager)
21+
22+
## Development
23+
24+
For development, we use a local container. This can be seen in the compose.yml file and the server.js file where we create a pool of connections. To run the sample locally after clonging the respository, you can run on docker by doing _docker compose up --build_ or run without using Docker by doing the following:
25+
26+
1. run npm install to install the nodejs dependencies
27+
2. create an .env file on the svelte directory specifying the appropriate environment variables.
28+
3. run npm start
29+
30+
### Editing the database/permissions etc.
31+
32+
If you want to edit the database, such that you can deploy them to production, you should [install the mySQL CLI](https://dev.mysql.com/doc/mysql-shell/8.0/en/mysql-shell-install-linux-quick.html) and mySQL workbench to gain access to a GUI so that you can make your changes to the database. After running defang compose up these changes will be reflected.
33+
34+
## Deploying
35+
36+
1. Open the terminal and type `defang login`
37+
2. Type `defang compose up` in the CLI.
38+
3. Your app will be running within a few minutes.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"name": "backend",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "script.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1",
8+
"start": "node script.js"
9+
},
10+
"keywords": [],
11+
"author": "",
12+
"license": "ISC",
13+
"dependencies": {
14+
"cors": "^2.8.5",
15+
"express": "^4.19.2",
16+
"mysql2": "^3.9.7"
17+
}
18+
}
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
const express = require('express');
2+
const mysql = require('mysql2');
3+
const cors = require('cors');
4+
const path = require('path');
5+
6+
const app = express();
7+
app.use(cors());
8+
app.use(express.json());
9+
10+
// Create a pool of connections
11+
const pool = mysql.createPool({
12+
host: process.env.DATABASE_HOST,
13+
user: process.env.DATABASE_USER,
14+
password: process.env.DATABASE_PASSWORD,
15+
database: process.env.DATABASE_NAME,
16+
waitForConnections: true,
17+
connectionLimit: 10,
18+
queueLimit: 0
19+
});
20+
21+
// Function to ensure 'tasks' table exists
22+
const ensureTasksTable = () => {
23+
const sql = `
24+
CREATE TABLE IF NOT EXISTS tasks (
25+
id INT AUTO_INCREMENT PRIMARY KEY,
26+
title VARCHAR(255) NOT NULL,
27+
completed BOOLEAN NOT NULL DEFAULT FALSE
28+
);
29+
`;
30+
pool.query(sql, (error, results) => {
31+
if (error) {
32+
console.error('Error ensuring tasks table exists:', error);
33+
return;
34+
}
35+
console.log('Tasks table checked/created.');
36+
});
37+
};
38+
39+
// Ensure the tasks table is created before starting the server
40+
pool.getConnection((err, connection) => {
41+
if (err) {
42+
console.error('Error connecting to the database:', err);
43+
process.exit(1);
44+
} else {
45+
console.log('Connected to the database.');
46+
ensureTasksTable();
47+
connection.release();
48+
49+
// Start the server only after ensuring the table exists
50+
const PORT = process.env.PORT || 3001;
51+
app.listen(PORT, () => {
52+
console.log(`Server running on port ${PORT}`);
53+
});
54+
}
55+
});
56+
57+
// API Routes
58+
app.get('/tasks', (req, res) => {
59+
pool.query('SELECT * FROM tasks', (error, results) => {
60+
if (error) {
61+
console.error(error);
62+
return res.status(500).json({ error: "Internal server error" });
63+
}
64+
res.json(results);
65+
});
66+
});
67+
68+
app.post('/tasks', (req, res) => {
69+
const { title } = req.body;
70+
pool.query('INSERT INTO tasks SET ?', { title, completed: false }, (error, results) => {
71+
if (error) {
72+
console.error(error);
73+
return res.status(500).json({ error: "Internal server error" });
74+
}
75+
res.status(201).json({ id: results.insertId, title, completed: false });
76+
});
77+
});
78+
79+
app.put('/tasks/:id', (req, res) => {
80+
const { id } = req.params;
81+
const { title, completed } = req.body;
82+
pool.query(
83+
'UPDATE tasks SET title = ?, completed = ? WHERE id = ?',
84+
[title, completed, id],
85+
(error, results) => {
86+
if (error) {
87+
console.error(error);
88+
return res.status(500).json({ error: "Internal server error" });
89+
}
90+
if (results.affectedRows === 0) {
91+
return res.status(404).json({ error: "Task not found" });
92+
}
93+
res.json({ id, title, completed });
94+
}
95+
);
96+
});
97+
98+
app.delete('/tasks/:id', (req, res) => {
99+
const { id } = req.params;
100+
pool.query('DELETE FROM tasks WHERE id = ?', [id], (error, results) => {
101+
if (error) {
102+
console.error(error);
103+
return res.status(500).json({ error: "Internal server error" });
104+
}
105+
res.send('Task deleted.');
106+
});
107+
});
108+
109+
// Serve static files from the "public" directory
110+
app.use(express.static(path.join(__dirname, 'public')));
111+
112+
// Serve the frontend from the root
113+
app.get('*', (req, res) => {
114+
res.sendFile(path.join(__dirname, 'public', 'index.html'));
115+
});
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
version: "3.8"
2+
name: svelte
3+
services:
4+
db:
5+
image: mysql:latest
6+
environment:
7+
MYSQL_ALLOW_EMPTY_PASSWORD: true
8+
MYSQL_DATABASE: todoApp
9+
MYSQL_USER: admin
10+
MYSQL_PASSWORD: Defang12345
11+
volumes:
12+
- mysql_data:/var/lib/mysql
13+
ports:
14+
- mode: host
15+
target: 3306
16+
17+
app:
18+
build: .
19+
restart: unless-stopped
20+
environment:
21+
DATABASE_HOST: db
22+
DATABASE_USER: admin
23+
DATABASE_PASSWORD: Defang12345
24+
DATABASE_NAME: todoApp
25+
ports:
26+
- "3001:3001"
27+
depends_on:
28+
- db
29+
30+
networks:
31+
default:
32+
name: backend-network
33+
34+
volumes:
35+
mysql_data:
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
engine-strict=true

0 commit comments

Comments
 (0)