visit
Node.js, MySQL, and Aptible are well-suited technologies for building scalable, performant, and secure streaming web apps.
CREATE DATABASE movie_db;
USE movie_db;
CREATE TABLE movies (
id INT AUTO_INCREMENT PRIMARY KEY,
image_url VARCHAR(255) NOT NULL,
video_url VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
genre VARCHAR(255) NOT NULL,
description TEXT,
rating DECIMAL(3, 1),
release_year INT
);
Please create a new Node.js
project folder and initialize it as a Node.js project.
mkdir movie-app
cd movie-app
npm init -y
npm install express mysql2 multer
express
: A popular Node.js framework for building web applications.mysql2
: A MySQL client for Node.js.multer
: Middleware for handling file uploads.In your Node.js
project, create a db.js
file to set up the MySQL database connection:
// db.js
const mysql = require('mysql2');
const db = mysql.createConnection({
host: 'localhost', // Change to your MySQL host
user: 'root', // Change to your MySQL username
password: 'password', // Change to your MySQL password
database: 'movie_db',
});
db.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err);
throw err;
}
console.log('Connected to the database');
});
const createTable = `
CREATE TABLE IF NOT EXISTS movies (
id INT AUTO_INCREMENT PRIMARY KEY,
image_url VARCHAR(255) NOT NULL,
video_url VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
genre VARCHAR(255) NOT NULL,
description TEXT,
rating DECIMAL(3, 1),
release_year INT
)
`;
db.query(createTable, (err) => {
if (err) {
console.error("Error creating movies table:", err);
} else {
console.log("Movies table created or already exists");
}
});
module.exports = db;
Replace 'your_username'
and 'your_password'
with your MySQL credentials.
In your Node.js project, create an app.js
file to define your API endpoints using Express:
// app.js
const express = require('express');
const db = require('./db'); // Import the database connection
const multer = require('multer');
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Configure Multer for handling file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, Date.now() + '-' + file.originalname);
},
});
const upload = multer({ storage });
// Create a new movie
app.post('/movies', upload.fields([{ name: 'image', maxCount: 1 }, { name: 'video', maxCount: 1 }]), (req, res) => {
const { title, genre, description, rating, release_year } = req.body;
const image_url = req.files['image'][0].path;
const video_url = req.files['video'][0].path;
const query = 'INSERT INTO movies (image_url, video_url, title, genre, description, rating, release_year) VALUES (?, ?, ?, ?, ?, ?, ?)';
const values = [image_url, video_url, title, genre, description, rating, release_year];
db.query(query, values, (err, result) => {
if (err) {
console.error('Error creating a movie:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else {
res.status(201).json({ message: 'Movie created successfully' });
}
});
});
// List all movies
app.get('/movies', (req, res) => {
const query = 'SELECT * FROM movies';
db.query(query, (err, rows) => {
if (err) {
console.error('Error listing movies:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else {
res.status(200).json(rows);
}
});
});
// Search movies
app.get('/movies/search', (req, res) => {
const { query } = req.query;
const searchQuery = `%${query}%`;
const searchSql = 'SELECT * FROM movies WHERE title LIKE ? OR genre LIKE ?';
const searchValues = [searchQuery, searchQuery];
db.query(searchSql, searchValues, (err, rows) => {
if (err) {
console.error('Error searching movies:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else {
res.status(200).json(rows);
}
});
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Base URL: //localhost:3000/
/movies
Body:
{
"title": "Movie Title",
"description": "Movie description goes here.",
"release_year": 2023,
"genre": "Action",
"rating": 8.5,
"image_url": "//example.com/movie-image.jpg",
"video_url": "//example.com/movie-video.mp4"
}
Status: 201 Created
Body:
jsonCopy code{
"message": "Movie created successfully"
/movies
Status: 200 OK
Body: An array of movie objects. Each object includes the following fields:
jsonCopy code[
{
"id": 1,
"title": "Movie Title 1",
"description": "Movie description goes here.",
"release_year": 2022,
"genre": "Drama",
"rating": 7.9,
"image_url": "//example.com/movie1-image.jpg",
"video_url": "//example.com/movie1-video.mp4"
},
{
"id": 2,
"title": "Movie Title 2",
"description": "Another movie description.",
"release_year": 2021,
"genre": "Comedy",
"rating": 6.8,
"image_url": "//example.com/movie2-image.jpg",
"video_url": "//example.com/movie2-video.mp4"
}
]
node app.js
Code folder structure
1: Create environment
Go to the Aptible dashboard and click on the Environments tab.
Click on the Create Environment button.
Click on the Create Environment button.
2: Create Database
In this tutorial, you will create a MySQL database.
To avoid this error
ERROR 1045 (28000): Access denied for user 'aptible'@'ip-[IP_ADDRESS].ec2.internal' (using password: YES)
ssl: { rejectUnauthorized: false, ciphers: "DHE-RSA-AES256-SHA" },
Complete db.js
const mysql = require("mysql2");
const db = mysql.createConnection({
host: "", // Change to your MySQL aptible host
user: "aptible", // Change to your MySQL username
password: "", // Change to your MySQL password
database: "db",
ssl: { rejectUnauthorized: false, ciphers: "DHE-RSA-AES256-SHA" },
port: 26038,
});
db.connect((err) => {
if (err) {
console.error("Error connecting to the database:", err);
throw err;
}
console.log("Connected to the database");
});
const createTable = `
CREATE TABLE IF NOT EXISTS movies (
id INT AUTO_INCREMENT PRIMARY KEY,
image_url VARCHAR(255) NOT NULL,
video_url VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
genre VARCHAR(255) NOT NULL,
description TEXT,
rating DECIMAL(3, 1),
release_year INT
)
`;
db.query(createTable, (err) => {
if (err) {
console.error("Error creating movies table:", err);
} else {
console.log("Movies table created or already exists");
}
});
module.exports = db;
3: Create an App
Then, create an App by giving the Handle a name, and click Save App
Once provisioning is complete, click on the app name and click Get Started to continue the deployment process.
4: Upload your SSH public key.
5: Create a Dockerfile
Sample Dockerfile here# Use the official Node.js image as the base image
FROM node:16
# Set the working directory inside the container
WORKDIR /app
# Copy package.json and package-lock.json to the working directory
COPY package*.json ./
# Install project dependencies
RUN npm install
# Copy the application code to the container
COPY . .
# Expose the port that the app will run on
EXPOSE 3000
# Start the application
CMD ["node", "app.js"]
6: Deploy to Aptible via Git remote
git remote add aptible [email protected]:env-prodzz/movieapp.git
git push aptible main
7: Add an Endpoint
Once the endpoint has been created, you can send a GET
, POST
, DELETE
, or any other supported HTTP method to the endpoint using an API testing platform.
8: Test your final project