mirror of
https://github.com/kmitresse/Compo-Service-Log-Project.git
synced 2026-05-13 17:11:49 +00:00
feat: fileService.ts
This commit is contained in:
+5
-1
@@ -2,7 +2,9 @@
|
|||||||
.idea/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|
||||||
# Dependencies
|
# Environment
|
||||||
|
.env
|
||||||
|
cache/
|
||||||
node_modules/
|
node_modules/
|
||||||
|
|
||||||
# Build files
|
# Build files
|
||||||
@@ -10,3 +12,5 @@ build/
|
|||||||
|
|
||||||
# OS Files
|
# OS Files
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# Ignore artifacts:
|
||||||
|
build
|
||||||
|
|
||||||
|
# Dependenciess
|
||||||
|
node_modules
|
||||||
|
cache
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"trailingComma": "es5",
|
||||||
|
"tabWidth": 2,
|
||||||
|
"semi": true,
|
||||||
|
"singleQuote": false
|
||||||
|
}
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
# Mit-Vab-Compo-Service-Logiciel
|
# Mit-Vab-Compo-Service-Logiciel
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Getting started
|
## Getting started
|
||||||
|
|
||||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||||
@@ -42,7 +40,7 @@ Use the built-in continuous integration in GitLab.
|
|||||||
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
||||||
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
||||||
|
|
||||||
***
|
---
|
||||||
|
|
||||||
# Editing this README
|
# Editing this README
|
||||||
|
|
||||||
@@ -53,30 +51,39 @@ When you're ready to make this README your own, just edit this file and use the
|
|||||||
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||||
|
|
||||||
## Name
|
## Name
|
||||||
|
|
||||||
Choose a self-explaining name for your project.
|
Choose a self-explaining name for your project.
|
||||||
|
|
||||||
## Description
|
## Description
|
||||||
|
|
||||||
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||||
|
|
||||||
## Badges
|
## Badges
|
||||||
|
|
||||||
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||||
|
|
||||||
## Visuals
|
## Visuals
|
||||||
|
|
||||||
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||||
|
|
||||||
## Support
|
## Support
|
||||||
|
|
||||||
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||||
|
|
||||||
## Roadmap
|
## Roadmap
|
||||||
|
|
||||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
State if you are open to contributions and what your requirements are for accepting them.
|
State if you are open to contributions and what your requirements are for accepting them.
|
||||||
|
|
||||||
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||||
@@ -84,10 +91,13 @@ For people who want to make changes to your project, it's helpful to have some d
|
|||||||
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||||
|
|
||||||
## Authors and acknowledgment
|
## Authors and acknowledgment
|
||||||
|
|
||||||
Show your appreciation to those who have contributed to the project.
|
Show your appreciation to those who have contributed to the project.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
For open source projects, say how it is licensed.
|
For open source projects, say how it is licensed.
|
||||||
|
|
||||||
## Project status
|
## Project status
|
||||||
|
|
||||||
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
||||||
|
|||||||
Generated
+1147
-1
File diff suppressed because it is too large
Load Diff
+18
-5
@@ -3,19 +3,32 @@
|
|||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "npm run build && npm run start",
|
"dev": "npm run format && npx ts-node ./src/index.ts",
|
||||||
"start": "node build/index.js",
|
"build": "npx tsc",
|
||||||
"build": "npx tsc"
|
"format": "npx prettier . --write --log-level warn"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"authors": [
|
||||||
|
"Kévin Mitressé",
|
||||||
|
"Lucàs Vabre"
|
||||||
|
],
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"description": "",
|
"description": "",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"express": "^4.21.0"
|
"axios": "^1.7.7",
|
||||||
|
"dmn-js": "^16.7.1",
|
||||||
|
"dotenv": "^16.4.5",
|
||||||
|
"express": "^4.21.0",
|
||||||
|
"fs-extra": "^11.2.0",
|
||||||
|
"unzipper": "^0.12.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/express": "^4.17.21",
|
||||||
|
"@types/fs-extra": "^11.0.4",
|
||||||
"@types/node": "^22.5.5",
|
"@types/node": "^22.5.5",
|
||||||
|
"@types/unzipper": "^0.10.10",
|
||||||
|
"prettier": "3.3.3",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
"typescript": "^5.6.2"
|
"typescript": "^5.6.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-1
@@ -1 +1,17 @@
|
|||||||
console.log('Hello world!')
|
import express from "express";
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
import { createServer } from "node:http";
|
||||||
|
import { logger } from "./middlewares";
|
||||||
|
import routes from "./routes";
|
||||||
|
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
app.use(logger, routes);
|
||||||
|
const server = createServer(app);
|
||||||
|
|
||||||
|
server.listen(process.env.PORT || 8080, () => {
|
||||||
|
console.info(
|
||||||
|
`Server is running on http://localhost:${process.env.PORT || 8080}`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
export { default as logger } from "./logger";
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { NextFunction, Request, Response } from "express";
|
||||||
|
|
||||||
|
export default function logger(
|
||||||
|
req: Request,
|
||||||
|
res: Response,
|
||||||
|
next: NextFunction
|
||||||
|
) {
|
||||||
|
console.info(`[${req.method}] ${req.url}`);
|
||||||
|
next();
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Router, Request, Response } from "express";
|
||||||
|
import fileService from "../../services/fileService";
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
router.get("/data/nudger", (req: Request, res: Response) => {
|
||||||
|
fileService
|
||||||
|
.downloadAndExtract("https://nudger.fr/opendata/gtin-open-data.zip")
|
||||||
|
.then(() => {
|
||||||
|
res.status(200).json({
|
||||||
|
status: "SUCCESS",
|
||||||
|
message: "Data nudger downloaded and extracted",
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
res.status(500).json({ status: "ERROR", message: error.message });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { Router, Request, Response } from "express";
|
||||||
|
import fileService from "../../services/fileService";
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
router.get("/data/openfoodfacts", (req: Request, res: Response) => {
|
||||||
|
fileService
|
||||||
|
.downloadAndExtract(
|
||||||
|
"https://static.openfoodfacts.org/data/en.openfoodfacts.org.products.csv.gz"
|
||||||
|
)
|
||||||
|
.then(() => {
|
||||||
|
res.status(200).json({
|
||||||
|
status: "SUCCESS",
|
||||||
|
message: "Data openfoodfacts downloaded and extracted",
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
res.status(500).json({ status: "ERROR", message: error.message });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import randomizeRouter from "./randomize";
|
||||||
|
import nudgerRouter from "./data/nudger";
|
||||||
|
import openDataRouter from "./data/openfoodfacts";
|
||||||
|
|
||||||
|
export default [randomizeRouter, nudgerRouter, openDataRouter];
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Router, Request, Response } from "express";
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
router.post("/randomize", (req: Request, res: Response) => {
|
||||||
|
// TODO: Implement randomize route
|
||||||
|
|
||||||
|
// TODO: Parse the DMN file
|
||||||
|
|
||||||
|
// TODO:
|
||||||
|
res.status(200).json({ status: "RANDOMIZED", data: [{}] });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import axios from "axios";
|
||||||
|
import * as unzipper from "unzipper";
|
||||||
|
import * as fs from "fs-extra";
|
||||||
|
import * as zlib from "zlib";
|
||||||
|
import { extname, join, basename } from "path";
|
||||||
|
import crypto from "crypto"; // Utilisé pour générer des identifiants uniques basés sur l'URL
|
||||||
|
|
||||||
|
type SupportedFormats = "zip" | "gz" | "gzip";
|
||||||
|
|
||||||
|
class FileService {
|
||||||
|
private cacheDir: string;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.cacheDir = "./cache";
|
||||||
|
fs.ensureDirSync(this.cacheDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Télécharger et extraire le fichier à partir de l'URL
|
||||||
|
* @param url URL du fichier à télécharger
|
||||||
|
*/
|
||||||
|
async downloadAndExtract(url: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
const fileType = this.getFileExtension(url);
|
||||||
|
if (!fileType) throw new Error("Unsupported file format");
|
||||||
|
if (this.isInCache(url)) return;
|
||||||
|
|
||||||
|
const response = await axios({
|
||||||
|
method: "GET",
|
||||||
|
url,
|
||||||
|
responseType: "stream",
|
||||||
|
});
|
||||||
|
console.log(`Downloading : ${url}`);
|
||||||
|
|
||||||
|
// Décompresser et sauvegarder dans le cache
|
||||||
|
const cacheKey = this.generateCacheKey(url);
|
||||||
|
const cachedPath = join(this.cacheDir, cacheKey);
|
||||||
|
|
||||||
|
fs.ensureDirSync(cachedPath);
|
||||||
|
|
||||||
|
if (fileType === "zip") await this.extractZip(response.data, cachedPath);
|
||||||
|
if (fileType === "gz" || fileType === "gzip")
|
||||||
|
await this.extractGzip(
|
||||||
|
response.data,
|
||||||
|
join(cachedPath, basename(url).replace(/\.(gz|gzip)$/, ""))
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(`Downloaded and extracted : ${basename(url)}`);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
"An error occurred while downloading and extracting the file",
|
||||||
|
error
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vérifier si le fichier est déjà en cache
|
||||||
|
* @param url URL du fichier
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
private isInCache(url: string): boolean {
|
||||||
|
const cacheKey = this.generateCacheKey(url);
|
||||||
|
const cachedPath = join(this.cacheDir, cacheKey);
|
||||||
|
return fs.pathExistsSync(cachedPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extraire les fichiers ZIP et stocker dans le cache
|
||||||
|
* @param stream
|
||||||
|
* @param cachePath
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
private async extractZip(
|
||||||
|
stream: NodeJS.ReadableStream,
|
||||||
|
cachePath: string
|
||||||
|
): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
stream
|
||||||
|
.pipe(unzipper.Extract({ path: cachePath }))
|
||||||
|
.on("close", resolve)
|
||||||
|
.on("error", reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extraire les fichiers GZ et GZIP et stocker dans le cache
|
||||||
|
* @param stream Flux du fichier téléchargé
|
||||||
|
* @param cachePath Chemin où stocker le fichier décompressé
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
private async extractGzip(
|
||||||
|
stream: NodeJS.ReadableStream,
|
||||||
|
cachePath: string
|
||||||
|
): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
// Ajouter une extension correcte (par exemple, si le fichier original est 'file.gz', le résultat sera 'file')
|
||||||
|
const decompressedFilePath = cachePath.replace(/\.gz$/, "");
|
||||||
|
|
||||||
|
const writeStream = fs.createWriteStream(decompressedFilePath);
|
||||||
|
|
||||||
|
// Pipeliner le flux du téléchargement et la décompression
|
||||||
|
stream
|
||||||
|
.pipe(zlib.createGunzip()) // Décompresser le flux
|
||||||
|
.pipe(writeStream) // Écrire le fichier décompressé
|
||||||
|
.on("finish", resolve)
|
||||||
|
.on("error", reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtenir l'extension du fichier à partir de l'URL
|
||||||
|
* @param url URL du fichier
|
||||||
|
*/
|
||||||
|
private getFileExtension(url: string): SupportedFormats | null {
|
||||||
|
const extension = extname(url).toLowerCase();
|
||||||
|
if (extension === ".zip") return "zip";
|
||||||
|
if (extension === ".gz" || extension === ".gzip") return "gz";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Générer un identifiant unique pour le fichier basé sur l'URL
|
||||||
|
* @param url URL du fichier
|
||||||
|
*/
|
||||||
|
private generateCacheKey(url: string): string {
|
||||||
|
return crypto.createHash("md5").update(url).digest("hex");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default new FileService();
|
||||||
@@ -3,24 +3,19 @@
|
|||||||
/* Language and Environment */
|
/* Language and Environment */
|
||||||
"target": "es2016",
|
"target": "es2016",
|
||||||
"lib": ["es6"],
|
"lib": ["es6"],
|
||||||
|
|
||||||
/* Modules */
|
/* Modules */
|
||||||
"module": "commonjs",
|
"module": "commonjs",
|
||||||
"rootDir": "src",
|
"rootDir": "src",
|
||||||
"resolveJsonModule": true,
|
"resolveJsonModule": true,
|
||||||
|
|
||||||
/* JavaScript Support */
|
/* JavaScript Support */
|
||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
"outDir": "build",
|
"outDir": "build",
|
||||||
|
|
||||||
/* Interop Constraints */
|
/* Interop Constraints */
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"forceConsistentCasingInFileNames": true,
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
|
||||||
/* Type Checking */
|
/* Type Checking */
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"noImplicitAny": true,
|
"noImplicitAny": true,
|
||||||
|
|
||||||
/* Completeness */
|
/* Completeness */
|
||||||
"skipLibCheck": true
|
"skipLibCheck": true
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user