Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify GET package endpoint to follow creates.io API specification + add DB #1

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
DB_NAME=noir_libs
DB_USER=your_username
DB_PASSWORD=your_password
DB_HOST=localhost
DB_PORT=5432
IS_PROD=false
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
"test:e2e": "jest --config ./test/jest-e2e.json",
"mikro-orm": "mikro-orm"
},
"dependencies": {
"@mikro-orm/core": "^6.4.1",
"@mikro-orm/migrations": "^6.4.1",
"@mikro-orm/nestjs": "^6.0.2",
"@mikro-orm/postgresql": "^6.4.1",
"@nestjs/common": "^10.0.0",
Expand All @@ -30,9 +32,11 @@
"dotenv": "^16.4.7",
"multer": "^1.4.5-lts.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
"rxjs": "^7.8.1",
"semver": "^7.6.3"
},
"devDependencies": {
"@mikro-orm/cli": "^6.4.1",
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
Expand Down
17 changes: 6 additions & 11 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UploadModule } from './upload/upload.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PackagesModule } from './packages/packages.module';
import MikroOrmConfig from './mikro-orm.config';

@Module({
imports: [UploadModule],
controllers: [AppController],
providers: [AppService],
})
import { UploadModule } from './upload/upload.module';

@Module({
imports: [
Expand All @@ -23,9 +18,9 @@ import MikroOrmConfig from './mikro-orm.config';
useFactory: async () => MikroOrmConfig,
inject: [ConfigService],
}),
UploadModule
PackagesModule, UploadModule
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
export class AppModule {}
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ async function bootstrap() {
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
credentials: true, // Enable if you need to send cookies or authentication data
});
await app.listen(process.env.PORT ?? 3000);
await app.listen(process.env.PORT ?? 3001);
}
bootstrap();
6 changes: 4 additions & 2 deletions src/mikro-orm.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@ import * as dotenv from 'dotenv';

dotenv.config();
const config: any = {
entities: ['./dist/model'],
entitiesTs: ['./src/model'],
entities: ['./dist/**/*.entity.js'],
entitiesTs: ['./src/**/*.entity.ts'],
dbName: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
host: process.env.DB_HOST,
port: Number(process.env.DB_PORT),
driver: PostgreSqlDriver,
debug: process.env.IS_PROD !== 'true',


};

export default config;
18 changes: 18 additions & 0 deletions src/model/download.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Entity, PrimaryKey, Property, ManyToOne } from '@mikro-orm/core';
import { Package } from './package.entity';
import { Version } from './version.entity';

@Entity()
export class Download {
@PrimaryKey()
id!: number;

@ManyToOne(() => Package)
package!: Package;

@ManyToOne(() => Version)
version!: Version;

@Property()
downloadDate: Date = new Date();
}
21 changes: 21 additions & 0 deletions src/model/package.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Entity, PrimaryKey, Property, Collection, OneToMany } from '@mikro-orm/core';
import { Version } from './version.entity';
import { Download } from './download.entity';

@Entity()
export class Package {
PeerZetZzZzZ marked this conversation as resolved.
Show resolved Hide resolved
@PrimaryKey()
name!: string;
PeerZetZzZzZ marked this conversation as resolved.
Show resolved Hide resolved

@Property()
tags!: string;

@Property({ type: 'text' })
readme?: string;

@OneToMany(() => Version, version => version.package)
versions = new Collection<Version>(this);

@OneToMany(() => Download, download => download.package)
downloads = new Collection<Download>(this);
}
23 changes: 23 additions & 0 deletions src/model/version.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Entity, PrimaryKey, Property, ManyToOne } from '@mikro-orm/core';
import { Package } from './package.entity';

@Entity()
export class Version {
@PrimaryKey()
id!: number;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make primary key as composite key <package, version> - it will be simpler and better index.
Is probably will work if you put @PrimaryKey() on id! and version! properties.


@ManyToOne(() => Package)
package!: Package;

@Property()
version!: string;

@Property({ columnType: 'text' })
packageBlob!: string;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe:

@Property({ type: 'blob' }) // Maps to BLOB in the database
data!: Buffer;

then we will use blob data. Here we store .tar.gz. It should be also easy to download file


@Property()
sizeKb!: number;

@Property()
createdAt: Date = new Date();
}
144 changes: 144 additions & 0 deletions src/packages/packages.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import {
Controller,
Get,
Param,
StreamableFile,
NotFoundException, Res,
BadRequestException
} from '@nestjs/common';
import { EntityManager } from '@mikro-orm/postgresql';
import { Package } from '../model/package.entity';
import { Response } from 'express';
import * as stream from 'stream';
import { Download } from 'src/model/download.entity';
import { Version } from 'src/model/version.entity';

@Controller('api/v1/packages')
export class PackagesController {
constructor(private readonly em: EntityManager) {}
@Get()
PeerZetZzZzZ marked this conversation as resolved.
Show resolved Hide resolved
async getAllPackages() {
const packages = await this.em.find(Package, {}, {
populate: ['versions']
});

return packages.map(pkg => ({
name: pkg.name,
tags: pkg.tags,
versions: pkg.versions.getItems().map(ver => ({
version: ver.version,
createdAt: ver.createdAt,
sizeKb: ver.sizeKb
}))
}));
}

@Get(':name/:version')
async getPackage(@Param('name') name: string, @Param('version') version: string) {
// const parsedVersion = semver.parse(version);

const pkg = await this.em.findOne(Package, { name }, { populate: ['versions'] });
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should be able to fetch package by name and version here already in 1 DB query

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have package name and version. We can do a fetch for specific package and version, not fetch whole versions. Pls fix it to avoid getting all versions. If you change primary keys to composite as I suggested above it will be index.

if (!pkg) {
throw new NotFoundException(`Package "${name}" not found`);
}

// if (!parsedVersion) {
// throw new BadRequestException('Invalid version format');
// }

// const { major, minor, patch } = parsedVersion;
const ver = pkg.versions.getItems().find(
v => v.version === version,
);

if (!ver) {
throw new NotFoundException(`Version "${version}" not found for package "${name}"`);
}

return {
name: pkg.name,
version: ver.version,
size_kb: ver.sizeKb,
readme: pkg.readme,
created_at: ver.createdAt,
tag_name: pkg.tags,
};
}


@Get(':name/:version/download')
async downloadPackage(
@Param('name') name: string,
@Param('version') version: string,
@Res() res: Response,
) {
const [major, minor, patch] = version.split('.').map(Number);

const pkg = await this.em.findOne(Package, { name }, { populate: ['versions'] });
if (!pkg) {
throw new NotFoundException(`Package "${name}" not found`);
}

const ver = pkg.versions.getItems().find(
v => v.version === version,
);

if (!ver) {
throw new NotFoundException(`Version "${version}" not found for package "${name}"`);
}

const download = new Download();
download.package = pkg;
download.version = ver;
await this.em.persistAndFlush(download);

const buffer = Buffer.from(ver.packageBlob, 'base64');
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably you will not have to do this if you change version entity to use blob (it will use Buffer)

const fileStream = new stream.PassThrough();
fileStream.end(buffer);

const fileName = `${name}-${version}.tar.gz`;
res.set({
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${fileName}"`,
'Content-Length': buffer.length,
});

fileStream.pipe(res);
}

@Get(':name/:version/downloads')
async getDownloadsHistory(
@Param('name') name: string,
@Param('version') version: string,
) {
const pkg = await this.em.findOne(Package, { name });
if (!pkg) {
throw new NotFoundException(`Package "${name}" not found`);
}


const ver = await this.em.findOne(Version, {
PeerZetZzZzZ marked this conversation as resolved.
Show resolved Hide resolved
package: {name: name.trim()},
version
});

if (!ver) {
throw new NotFoundException(`Version "${version}" not found for package "${name}"`);
}

const downloads = await this.em.find(Download, {
package: pkg,
version: ver
}, {
orderBy: { downloadDate: 'DESC' }
});

return {
package: name,
version: version,
downloads: downloads.map(download => ({
downloadDate: download.downloadDate
}))
};
}
}
17 changes: 17 additions & 0 deletions src/packages/packages.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { PackagesController } from './packages.controller';
import { PackagesService } from './packages.service';
import { Package } from '../model/package.entity';
import { Version } from '../model/version.entity';
import { Download } from '../model/download.entity';

@Module({
imports: [
MikroOrmModule.forFeature([Package, Version, Download])
],
controllers: [PackagesController],
providers: [PackagesService],
exports: [PackagesService],
})
export class PackagesModule {}
52 changes: 52 additions & 0 deletions src/packages/packages.service.ts
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pls remove this service from PR (keep the code for later).
We will create first packages manually, later we will add "upload" support :)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove this file pls for now from PR. We don't support it now.

Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Injectable } from '@nestjs/common';
import { EntityManager } from '@mikro-orm/postgresql';
import { Package } from '../model/package.entity';
import { Version } from '../model/version.entity';

@Injectable()
export class PackagesService {
constructor(private readonly em: EntityManager) {}

async findOrCreatePackage(name: string): Promise<Package> {
let pkg = await this.em.findOne(Package, { name });

if (!pkg) {
pkg = this.em.create(Package, { name, tags: '', readme: '' });
await this.em.persistAndFlush(pkg);
}

return pkg;
}

async addVersion(
packageId: number,
versionData: {
major: number;
minor: number;
patch: number;
versionNumber: string;
packageBlob: string;
sizeKb: number;
},
): Promise<Version> {
const pkg = await this.em.findOneOrFail(Package, packageId, { populate: ['versions'] });

const existingVersion = await this.em.findOne(Version, {
package: pkg,
});

if (existingVersion) {
throw new Error('Version already exists');
}

const version = this.em.create(Version, {
...versionData,
package: pkg,
});

pkg.versions.add(version);
await this.em.persistAndFlush(version);

return version;
}
}
18 changes: 0 additions & 18 deletions src/upload/upload.controller.spec.ts

This file was deleted.

Loading