1. NEXT vs REACT
REACT | NEXT |
- Library | - React Framework |
- Client-side Rendering (HTML sent to browser, and subsequent updates rendered on browser | - Server-side Rendering (Rendered on Server-side before sending to client) and Static Site Generation (Pre-rendered at buildtime |
- No built-in routing - Third-party library for routing (ex. React Router) |
- File System based Routing ('pages' directory determines URL) |
2. MEMORY STRUCTURE
- CODE: 프로그램이 끝날때까지 계속 메모리에 남음
- DATA: Global & Static Variables
- HEAP: Dynamically Allocated (new, malloc, etc) --> OBJECTS & DS
possible errors: memory leak and dangling pointer
- STACK: Local Variables & Function Parameters/Calls
3. DOCKER: Package an application and dependencies into a container -->
build, deploy, and run applications by using containers (isolated package) in MSA.
Container: A container is a lightweight, standalone, and executable package that includes everything needed to run a piece of software, including the code, runtime, dependencies, libraries, and system tools.
Image: An image is a read-only template used to create containers. It contains the application code and its dependencies. Images are used to create and run containers.
Dockerfile: A Dockerfile is a script that contains instructions to build a Docker image. It specifies the base image, configuration, and steps to install and configure the application.
1. Create a 'Dockerfile' Script
2. Build the Docker image using the following command:
docker build -t my-node-app .
3. Run the Docker container
docker run -p 3000:3000 my-node-app

4. Scripting Language: Python, JS, Ruby, PHP, Shell
- Scripting languages are INTERPRETED (src code run line by line by interpreter), NOT compiled (machine code)
- Dynamically typed --> var types determined at run time (type checking at run time --> slow)
5. ORM: Enable developers to work with OOP in RDBMS by object-relational mapping vs ODM: OOP in NoSQL
ORM | ODM |
OOP in RDBMS (mapping) | OOPS in NoSQL (mapping) |
Java: Hibernate, EclipseLink, MyBatis. Python: Django ORM, SQLAlchemy. |
Mongoose (MongoDB + Node.js) |
ODM Steps:
// server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mern-stack-db', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Middleware
app.use(bodyParser.json());
// Routes
app.get('/', (req, res) => {
res.send('Hello MERN Stack!');
});
// Start server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
// models/todo.js
Create MongoDB models using Mongoose to define the schema for your data.
//-----------------------------------------------------------------------------
const mongoose = require('mongoose');
const { Schema } = mongoose;
// 1. DEFINE A MONGOOSE SCHEMA
const userSchema = new Schema({
username: { type: String, required: true },
email: { type: String, required: true },
age: Number,
});
// 2. CREATE A MONGOOSE MODEL BASED ON SCHEMA
const User = mongoose.model('User', userSchema);
// 3. CREATE AND SAVE A DOCUMENT
const newUser = new User({ username: 'john_doe', email: 'john.doe@example.com', age: 25 });
newUser.save()
.then(doc => console.log('Document saved:', doc))
.catch(err => console.error('Error saving document:', err));
// routes/todos.js
Implement CRUD operations using Express.js routes and MongoDB models.
const express = require('express');
const Todo = require('../models/todo');
const router = express.Router();
// Get all todos
router.get('/todos', async (req, res) => {
try {
const todos = await Todo.find();
res.json(todos);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// Create a new todo
router.post('/todos', async (req, res) => {
const todo = new Todo({
text: req.body.text,
completed: req.body.completed || false,
});
try {
const newTodo = await todo.save();
res.status(201).json(newTodo);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
// Other CRUD operations (update, delete) can be added similarly
module.exports = router;
6. MIDDLEWARE: functions in server.js that have access to the request, response, and the next() middleware function in the application's request-response cycle. Middleware functions can perform tasks such as 1) processing the request, 2) modifying the response, or 3) executing additional logic before the request reaches the final route handler. Use cases in MERN:
- Logging/Error handling, Body Parsing (incoming reqs), Authentication, CORS, static file serving
7. WEB SERVER: Web servers are responsible for handling HTTP requests from clients and responding with the appropriate content (static and dynamic) and resources. Also: manage connections, load balancing, and caching
8. LOAD BALANCING: Distribute incoming traffic across multiple servers to optimize performance and workload
ex) Create an array of servers --> Use round-robin load balancing algo --> Proxy middleware (express-http-proxy) to balance load --> Ensure different port #
examples in SaaS: Reverse Proxy (NGINX), Container Orchestrators (Kubernetes)
9. CACHING: Storing copies of frequently requested data to reduce response times and improve overall performance.
ex) Create middleware to check for cached responses before processing requests (if found, return cached resposne) --> Use Cache Library (node-cache) --> app.use(cacheMiddleware) in express server.js
10. TCP vs UDP:
TCP | UDP |
- Connection-oriented (3-way) - Reliable Data Transfer (ack, sequencing, retransmission of lost packets) - Flow control, ordered, error-checking - Full-duplex (bidirectional) |
- Connectionless - Independent packets (no order) - No flow-control, error-checking - Use-case: real-time apps (game, streaming, etc) |
11. WEB SECURITY: Protect against unathorized attacks, injection attacks, etc.
CORS middleware allows/restricts cross-origin requests by setting appropriate headers to allow certain origins, etc.
CORS Example--> res.header('Access-Control-Allow-Origin', '*');
Authentication: verifies the identity of a user (ex. JWT authentication in Express.js)
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
// Secret key for JWT
const secretKey = 'mySecretKey';
// Route for generating a JWT token (login)
app.post('/login', (req, res) => {
// Authenticate user (in a real app, check username and password)
const user = { username: 'john_doe' };
// Generate a JWT token
const token = jwt.sign(user, secretKey);
res.json({ token });
});
Authorization: grants access based on the user's permissions.
// Secret key for JWT
const secretKey = 'mySecretKey';
// Middleware to verify JWT token
const authenticateToken = (req, res, next) => {
const token = req.header('Authorization');
if (!token) return res.sendStatus(401);
// user object is signed with a secret key to create a JWT, which is then sent to the client.
jwt.verify(token, secretKey, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
};
// Route that requires authentication
app.get('/protected', authenticateToken, (req, res) => {
res.json({ message: 'This is a protected route.' });
});
12. ASYNCHRONOUS PROGRAMMING: Node.js non-blocking I/O model --> 메인 쓰레드를 블로킹 하지 않고 여러개의 작업을 동시수행
- Callbacks --> Pass result after setTimeout()
- Promise Object --> Reject/Resolve
- Async/Await
13. FUND ACCOUNTING
Architecture Overview:
1. Fund Accounting and Business Logic (Pro*C, C):
Implement business logic for fund accounting and fund management.
Pro*C is used for embedding SQL in C code for Oracle database interaction.
The business logic layer handles computations, validations, and rules related to fund transactions, accounting, etc
/* fund_logic.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlca.h>
/* Function to calculate net asset value (NAV) */
void calculateNAV(int fundId, double *nav) {
EXEC SQL BEGIN DECLARE SECTION;
int fundId;
double nav;
EXEC SQL END DECLARE SECTION;
EXEC SQL SELECT SUM(transaction_amount) INTO :nav
FROM transactions
WHERE fund_id = :fundId;
/* Additional logic for expense ratio, dividends, etc. */
}
/* Main program */
int main() {
int fundId = 123;
double nav;
calculateNAV(fundId, &nav);
printf("Fund ID: %d, NAV: %.2f\n", fundId, nav);
return 0;
}
2. Fund Data and Ledger Management (Oracle DB, PL/SQL):
Utilize Oracle Database for storing and managing fund data.
PL/SQL is employed for writing stored procedures, triggers, and functions to implement database-related operations.
Maintain transaction ledgers, fund positions, and other relevant data structures.
-- fund_ledger_mgmt.sql
CREATE TABLE transactions (
transaction_id NUMBER PRIMARY KEY,
fund_id NUMBER,
transaction_type VARCHAR2(20),
transaction_amount NUMBER,
transaction_date DATE
);
CREATE OR REPLACE PROCEDURE insertTransaction (
p_fund_id IN NUMBER,
p_type IN VARCHAR2,
p_amount IN NUMBER,
p_date IN DATE
) AS
BEGIN
INSERT INTO transactions (transaction_id, fund_id, transaction_type, transaction_amount, transaction_date)
VALUES (transaction_seq.NEXTVAL, p_fund_id, p_type, p_amount, p_date);
COMMIT;
END insertTransaction;
3. Fund Data Transmission and Transaction Processing (Batch, Unix):
Implement batch processes for handling fund data transmission, transaction processing, and external interface coordination. Use Unix shell scripting for orchestrating batch jobs and managing file operations.
Handle data exchange with external systems and ensure transactional integrity.
#!/bin/bash
# fund_batch_process.sh
# Set environment variables, paths, etc.
export ORACLE_HOME=/path/to/oracle
export PATH=$PATH:$ORACLE_HOME/bin
# Run Pro*C compilation
proc iname=fund_batch_process.pc
gcc -o fund_batch_process fund_batch_process.c -L$ORACLE_HOME/lib -lclntsh -lm -lpthread -ldl -lresolv -lsql
# Run batch process
./fund_batch_process
# Additional file operations, data transmission, etc.
14. MERN Stack SaaS Platform
1. FRONTEND (REACT): This component captures user input (text or speech) and sends it to the backend for processing.
import React, { useState } from 'react';
import SpeechRecognition from 'react-speech-recognition';
import axios from 'axios';
const App = ({ transcript, resetTranscript, startListening, stopListening }) => {
const [textInput, setTextInput] = useState('');
const handleTextSubmit = async () => {
try {
// Send text input to backend for processing
const response = await axios.post('/api/generate-video', { text: textInput });
// Handle response as needed (e.g., update UI)
console.log(response.data);
} catch (error) {
console.error('Error processing text:', error);
}
};
return (
<div>
<textarea value={textInput} onChange={(e) => setTextInput(e.target.value)} />
<button onClick={handleTextSubmit}>Generate Video</button>
{/* Speech recognition controls */}
<button onClick={startListening}>Start Listening</button>
<button onClick={stopListening}>Stop Listening</button>
<button onClick={resetTranscript}>Reset Transcript</button>
{/* Display speech-to-text transcript */}
<div>{transcript}</div>
</div>
);
};
export default SpeechRecognition(App);
2. Backend (Node.js with Express) --> Sets up the Express server, connects to MongoDB, and defines middleware and routes.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const generateVideoRouter = require('./routes/generateVideo');
const app = express();
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/your-database-name', { useNewUrlParser: true, useUnifiedTopology: true });
// Middleware
app.use(bodyParser.json());
// Routes
app.use('/api', generateVideoRouter);
// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
3. Generate Video Route (routes/generateVideo.js): Implements a route for generating video content based on user input. Utilizes TTS and ChatGPT APIs.
const express = require('express');
const axios = require('axios');
const router = express.Router();
router.post('/generate-video', async (req, res) => {
try {
// Call TTS API to convert text to speech
const ttsResponse = await axios.post('TTS_API_URL', { text: req.body.text });
// Call ChatGPT API for generating video content based on user input
const chatGptResponse = await axios.post('CHATGPT_API_URL', { input: req.body.text });
// Additional logic for video generation and storage
// Respond to the client
res.json({ success: true, videoUrl: 'URL_TO_GENERATED_VIDEO' });
} catch (error) {
console.error('Error generating video:', error);
res.status(500).json({ success: false, error: 'Internal Server Error' });
}
});
module.exports = router;
'LEETCODE' 카테고리의 다른 글
#54. Spiral Matrix (0) | 2023.11.01 |
---|---|
#62. Unique Paths (1) | 2023.11.01 |
#55. Jump Game (0) | 2023.11.01 |
#53. Maximum Subarray (0) | 2023.11.01 |
#34. Find First and Last Position of Element in Sorted Array (0) | 2023.11.01 |