Skip to content

Commit 1c3d6b9

Browse files
authored
Merge pull request #3 from klerick/3.x.x-json-api
feat(json-api-nestjs): new-version 3.x.x
2 parents b8f032c + 075083d commit 1c3d6b9

File tree

3 files changed

+193
-6
lines changed

3 files changed

+193
-6
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
## Description
1919

2020
<p>
21-
This is the plugin that works upon TypeOrm library as a main database abstraction layer tool. Module automaticly generates API according to JSON API specificaton from the database structure (TypeORM entities). It support such features as requests validation based on database fields types, request filtering, endpoints exdending, data relations control and much more. Our module significantly reduces the development time of REST services by removing the need to negotiate the mechanism of client-server interaction and implementing automatic API generation without the need to write any code.
21+
This plugin works upon TypeOrm library, which is used as the main database abstraction layer tool. The module automatically generates an API according to JSON API specification from the database structure (TypeORM entities). It supports features such as requests validation based on database fields types, request filtering, endpoints extending, data relations control and much more. Our module significantly reduces the development time of REST services by removing the need to negotiate the mechanism of client-server interaction and implementing automatic API generation without the need to write any code.
2222
</p>
2323

2424
## Installation

libs/json-api-nestjs/README.md

Lines changed: 93 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,99 @@
1+
12
# json-api-nestjs
23

3-
This library was generated with [Nx](https://nx.dev).
4+
## Installation
5+
6+
```bash
7+
$ npm install json-api-nestjs
8+
```
9+
10+
## Example
11+
12+
Once the installation process is complete, we can import the **JsonApiModule** into the root **AppModule**.
13+
14+
```typescript
15+
import { Module } from '@nestjs/common';
16+
import { JsonApiModule } from 'json-api-nestjs';
17+
import { Users } from 'database';
18+
19+
@Module({
20+
imports: [
21+
JsonApiModule.forRoot({
22+
entities: [Users]
23+
}),
24+
],
25+
})
26+
export class AppModule {}
27+
```
28+
After this, you have prepare crude with ready to use end point:
29+
30+
31+
- GET /users
32+
- POST /users
33+
- GET /users/:id
34+
- PATCH /users/:id
35+
- DELETE /users/:id
36+
- GET /users/{id}/relationships/{relName}
37+
- POST /users/{id}/relationships/{relName}
38+
- PATCH /users/{id}/relationships/{relName}
39+
- DELETE /users/{id}/relationships/{relName}
40+
41+
## Configuration params
42+
43+
The following interface is using for the configuration:
44+
```typescript
45+
export interface ModuleOptions {
46+
entities: Entity[]; // List of typeOrm Entity
47+
controllers?: NestController[]; // List of controller, if you need extend default present
48+
connectionName?: string; // Type orm connection name: "default" is default name
49+
providers?: NestProvider[]; // List of addition provider for useing in custom controller
50+
options?: {
51+
requiredSelectField?: boolean; // Need list of select field in get endpoint, try is default
52+
debug?: boolean; // Debug info in result object
53+
};
54+
}
55+
```
56+
You can extend default controller:
57+
```typescript
58+
import { Get, Param, Inject, BadRequestException } from '@nestjs/common';
59+
60+
import { Users } from 'database';
61+
import {
62+
JsonApi,
63+
excludeMethod,
64+
JsonBaseController,
65+
InjectService,
66+
JsonApiService,
67+
QueryParams,
68+
} from 'json-api-nestjs';
69+
import { ExampleService } from '../../service/example/example.service';
70+
71+
@JsonApi(Users, {
72+
allowMethod: excludeMethod(['deleteRelationship']),
73+
requiredSelectField: true,
74+
})
75+
export class ExtendUserController extends JsonBaseController<Users> {
76+
@InjectService() public service: JsonApiService<Users>;
77+
@Inject(ExampleService) protected exampleService: ExampleService;
78+
79+
public override getAll(query: QueryParams<Users>) {
80+
if (!this.exampleService.someCheck(query)) {
81+
throw new BadRequestException({});
82+
}
83+
return this.service.getAll({ query });
84+
}
85+
86+
@Get(':id/example')
87+
testOne(@Param('id') id: string): string {
88+
return this.exampleService.testMethode(id);
89+
}
90+
}
91+
```
492

5-
## Building
93+
## Swagger UI
694

7-
Run `nx build json-api-nestjs` to build the library.
95+
For using swagger, you should only add [@nestjs/swagger](https://docs.nestjs.com/openapi/introduction)
896

9-
## Running unit tests
97+
## Reference Example
1098

11-
Run `nx test json-api-nestjs` to execute the unit tests via [Jest](https://jestjs.io).
99+
[example](https://github.com/klerick/nestjs-json-api/tree/master/apps/example) is an example project that demonstrates the usage of this module.
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
const glob = require('glob')
2+
const path = require('path')
3+
const fs = require('fs-extra')
4+
const {execSync} = require('child_process')
5+
const { createReporter } = require('istanbul-api');
6+
const istanbulCoverage = require('istanbul-lib-coverage');
7+
8+
const coverageDir = path.resolve(process.cwd(), 'coverage')
9+
const mergedDir = path.resolve(coverageDir, 'merged')
10+
11+
fs.emptyDirSync(mergedDir)
12+
const files = glob(coverageDir + '/**/*.xml', {sync: true})
13+
const exludeFromName = ['apps', 'libs']
14+
15+
files.forEach((f, i) => {
16+
const x = f.split('/coverage/')[1].replace(/\//g, '-').split('/').pop()
17+
.split('-').filter(i => i !== 'apps' && i !== 'libs' && i !== 'cobertura').join('-')
18+
fs.copySync(f, `${mergedDir}/${x}`)
19+
})
20+
21+
const filesMerged = glob(mergedDir + '/**/*.xml', {sync: true})
22+
23+
const packages = filesMerged
24+
.map((f, i) => {
25+
const fileName = path.basename(f)
26+
const projectName = fileName.split('-')
27+
projectName.pop()
28+
29+
return `${projectName.join('-')}=${fileName}`
30+
})
31+
.join(' ')
32+
33+
34+
35+
const script = `npx cobertura-merge -o merged-cobertura-coverage.xml ${packages}`
36+
37+
execSync(script, {
38+
stdio: [0, 1, 2],
39+
cwd: mergedDir,
40+
})
41+
42+
43+
const reporter = createReporter();
44+
45+
/* [ Configuration ] */
46+
const rootDir = './coverage';
47+
const reportOut = './coverage/report';
48+
49+
const normalizeJestCoverage = ( obj ) => {
50+
const result = { ...obj };
51+
52+
Object
53+
.entries( result )
54+
.filter( ([k, v] ) => v.data )
55+
.forEach( ([k, v] ) => {
56+
result[k] = v.data;
57+
});
58+
59+
return result;
60+
};
61+
62+
const mergeAllReports = ( coverageMap, reports ) => {
63+
if ( Array.isArray( reports ) === false ) {
64+
return;
65+
}
66+
67+
reports.forEach( reportFile => {
68+
const coverageReport = fs.readJSONSync( reportFile );
69+
coverageMap.merge( normalizeJestCoverage( coverageReport ) );
70+
})
71+
};
72+
73+
const findAllCoverageReports = ( path, callback ) => {
74+
glob( path, {}, ( err, reports )=>{
75+
callback( reports, err );
76+
});
77+
};
78+
79+
const generateReport = ( coverageMap, types ) => {
80+
reporter.dir = reportOut;
81+
reporter.addAll(types || ['html', 'text'] );
82+
reporter.write( coverageMap );
83+
};
84+
85+
async function main () {
86+
const coverageMap = istanbulCoverage.createCoverageMap( {} );
87+
88+
findAllCoverageReports( rootDir + '/**/coverage-final.json', ( reports, err ) => {
89+
if ( Array.isArray( reports ) ) {
90+
mergeAllReports( coverageMap, reports );
91+
generateReport( coverageMap, [ 'text' ] )
92+
}
93+
});
94+
}
95+
96+
main().catch(err => {
97+
console.error(err);
98+
process.exit(1);
99+
});

0 commit comments

Comments
 (0)