Menangani file upload dan mengintegrasikannya dengan Odoo Await di NestJS

Mengelola File Upload dengan Odoo Await di NestJS
Untuk menangani file upload dan mengintegrasikannya dengan Odoo Await di NestJS, Anda dapat memanfaatkan Multer untuk menangani upload file di server, kemudian menggunakan Odoo Await untuk mengunggah file tersebut ke Odoo.
Langkah 1: Persiapkan NestJS dengan Multer
Kita akan menggunakan Multer untuk menangani upload file. File yang diunggah akan disimpan sementara di server sebelum dikirim ke Odoo.
1.1 Instalasi Dependencies
Pastikan Multer dan @nestjs/platform-express telah terinstal:
npm install @nestjs/platform-express multer
1.2 Buat Controller untuk Upload File
Buat controller untuk menangani upload file dan mengirimnya ke Odoo.
upload.controller.ts
import { Controller, Post, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import * as path from 'path';
import { OdooProvider } from 'src/odoo/providers/odoo.provider'; // Pastikan path benar
@Controller('upload')
export class UploadController {
constructor(private readonly odooProvider: OdooProvider) {}
@Post('image')
@UseInterceptors(
FileInterceptor('file', {
storage: diskStorage({
destination: './uploads', // Direktori penyimpanan sementara
filename: (req, file, callback) => {
const ext = path.extname(file.originalname);
const filename = Date.now() + ext;
callback(null, filename);
},
}),
}),
)
async uploadImage(@UploadedFile() file: Express.Multer.File) {
try {
const odoo = await this.odooProvider.connect();
const result = await this.uploadFileToOdoo(odoo, file);
return result;
} catch (error) {
console.error(error);
throw new Error('File upload to Odoo failed');
}
}
private async uploadFileToOdoo(odoo: any, file: Express.Multer.File) {
try {
const fileContent = Buffer.from(file.buffer); // Konversi buffer ke konten
const filename = file.originalname;
const attachment = await odoo.create('ir.attachment', {
name: filename,
type: 'binary',
datas: fileContent.toString('base64'), // Base64 encoding
res_model: 'res.partner', // Model yang terhubung
res_id: 1, // ID model
});
return { message: 'File uploaded to Odoo successfully', attachment };
} catch (error) {
console.error('Odoo upload failed:', error);
throw new Error('Failed to upload file to Odoo');
}
}
}
Langkah 2: Konfigurasi Odoo Provider
Pastikan Anda memiliki provider untuk menghubungkan ke Odoo.
odoo.provider.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as Odoo from 'odoo-await';
interface OdooConfig {
baseUrl: string;
db: string;
username: string;
password: string;
}
@Injectable()
export class OdooProvider {
private odoo: Odoo;
constructor(private configService: ConfigService) {
const config: OdooConfig = {
baseUrl: this.configService.get<string>('ODOO_BASE_URL'),
db: this.configService.get<string>('ODOO_DB'),
username: this.configService.get<string>('ODOO_USERNAME'),
password: this.configService.get<string>('ODOO_PASSWORD'),
};
this.odoo = new Odoo(config);
}
async connect(): Promise<Odoo> {
await this.odoo.connect();
return this.odoo;
}
}
Langkah 3: Menyambungkan File ke Model Odoo
Dalam contoh ini, kita menggunakan model ir.attachment untuk menyimpan file di Odoo.
Hal yang Perlu Diperhatikan:
- Format File: Odoo menyimpan file dalam format Base64.
- Model yang Digunakan:
ir.attachment
adalah model default untuk file di Odoo. - Res Model & Res ID: Sesuaikan model dan ID dengan kebutuhan (misalnya
res.partner
).
Langkah 4: Pengujian
Menggunakan Postman atau Insomnia
- Endpoint:
POST /upload/image
- Form Data:
- Key:
file
- Value: Pilih file gambar untuk diuji
- Key:
Jika berhasil, response akan berisi informasi file yang diunggah ke Odoo.
Langkah 5: Menyediakan File Statis (Opsional)
Jika ingin mengakses file yang di-upload di frontend, gunakan express.static untuk menyajikan file secara statis:
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ServeStaticMiddleware } from '@nestjs/serve-static';
import { join } from 'path';
@Module({})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(ServeStaticMiddleware).forRoutes('/uploads');
}
}
Ringkasan:
✅ Multer digunakan untuk menangani upload file di NestJS. ✅ File dikonversi menjadi Base64 sebelum dikirim ke Odoo. ✅ Menggunakan model ir.attachment di Odoo untuk menyimpan file. ✅ Odoo Await digunakan untuk terhubung ke Odoo dan melakukan operasi CRUD terhadap file.
Dengan langkah-langkah ini, Anda dapat menangani file upload di NestJS dan mengintegrasikannya dengan Odoo Await untuk mengunggah file ke Odoo.