Skip to content

Commit

Permalink
fixed format issues
Browse files Browse the repository at this point in the history
  • Loading branch information
behzodfaiziev committed Oct 2, 2024
1 parent cec172c commit 75b2964
Show file tree
Hide file tree
Showing 10 changed files with 103 additions and 109 deletions.
42 changes: 21 additions & 21 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
{
"printWidth": 120,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always",
"requirePragma": false,
"insertPragma": false,
"proseWrap": "preserve",
"bracketSameLine": false,
"cursorOffset": -1,
"embeddedLanguageFormatting": "auto",
"endOfLine": "lf",
"htmlWhitespaceSensitivity": "css",
"jsxSingleQuote": true,
"quoteProps": "as-needed",
"singleAttributePerLine": false,
"vueIndentScriptAndStyle": false
}
"printWidth": 120,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always",
"requirePragma": false,
"insertPragma": false,
"proseWrap": "preserve",
"bracketSameLine": false,
"cursorOffset": -1,
"embeddedLanguageFormatting": "auto",
"endOfLine": "lf",
"htmlWhitespaceSensitivity": "css",
"jsxSingleQuote": true,
"quoteProps": "as-needed",
"singleAttributePerLine": false,
"vueIndentScriptAndStyle": false
}
30 changes: 17 additions & 13 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ return this.networkManager.request<SignInResponseDto>({

- made `config` optional in `request` method

## [0.5.2-dev] Note: This version has breaking changes.
## [0.5.2-dev] Note: This version has breaking changes.

- updated `request` to get `url` and `data` directly from params
Here is an example of how to use the new `request` method:
Expand All @@ -40,7 +40,8 @@ return this.networkManager.request<SignInResponseDto>({
return this.networkManager.request<SignInResponseDto>({
method: RequestMethod.POST,
config: {
url: `/api/auth/sign-in`, data: dto,
url: `/api/auth/sign-in`,
data: dto,
},
});
/// After
Expand All @@ -55,7 +56,7 @@ return this.networkManager.request<SignInResponseDto>({

- fixed importing issues

## [0.5.0-dev] Note: This version has breaking changes.
## [0.5.0-dev] Note: This version has breaking changes.

- added `RequestMethod` enum to define request methods so that it make the code more stable
- Deprecated: `request` method no longer accepts positional parameters. It now accepts named
Expand All @@ -74,7 +75,8 @@ return this.networkManager.request<SignInResponseDto>({
return this.networkManager.request<SignInResponseDto>({
method: RequestMethod.POST,
config: {
url: `/api/v1/auth/sign_in`, data: dto,
url: `/api/v1/auth/sign_in`,
data: dto,
},
});
```
Expand All @@ -100,6 +102,7 @@ return this.networkManager.request<SignInResponseDto>({
with the new Prettier configuration. by @remidosol

## [0.3.3]

- Exported `ApiException` class

## [0.3.2]
Expand All @@ -113,24 +116,24 @@ return this.networkManager.request<SignInResponseDto>({

```typescript
const networkManagerInstance = new NetworkManager({
baseUrl: 'https://api.example.com', // Production base URL
devBaseUrl: 'https://dev.example.com', // Development base URL
baseUrl: "https://api.example.com", // Production base URL
devBaseUrl: "https://dev.example.com", // Development base URL
testMode: false, // Test mode: false (production), true (development)
baseOptions: {}, // Axios config options
errorParams: networkErrorParams, // Error parameters
isClientSideWeb: typeof window !== 'undefined' && typeof localStorage !== 'undefined'
isClientSideWeb: typeof window !== "undefined" && typeof localStorage !== "undefined",
});
```

`Deprecated` usage:

```typescript
const networkManager = new NetworkManager(
'https://api.example.com', // Production base URL
'https://dev.example.com', // Development base URL
false, // Test mode: false (production), true (development)
{}, // Axios config options
networkErrorParams // Error parameters
"https://api.example.com", // Production base URL
"https://dev.example.com", // Development base URL
false, // Test mode: false (production), true (development)
{}, // Axios config options
networkErrorParams // Error parameters
);
```

Expand All @@ -139,9 +142,11 @@ const networkManager = new NetworkManager(
- added `isClientSideWeb` method to check if the code is running on the client side web

## [0.2.1]

- fixed importing issue in next applications

## [0.2.0]

- added both esnext and commonjs supports

## [0.1.4]
Expand All @@ -167,4 +172,3 @@ const networkManager = new NetworkManager(

- Added setAccessToken and setRefreshToken methods to save in local storage
- improved internal handling of baseUrl

100 changes: 47 additions & 53 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,30 +51,30 @@ You can create an instance of NetworkManager by passing the base URLs, mode
(development or production), Axios configuration options, and error-handling parameters.

```typescript
import {NetworkErrorParams, NetworkManager} from 'next-netkit';
import { NetworkErrorParams, NetworkManager } from "next-netkit";

// Define your error-handling parameters
const networkErrorParams: NetworkErrorParams = {
messageKey: 'message',
statusCodeKey: 'status',
couldNotParseError: 'Could not parse error',
jsonIsEmptyError: 'JSON is empty',
noInternetError: 'No internet connection',
jsonNullError: 'JSON is null',
jsonUnsupportedObjectError: 'JSON is unsupported object',
notMapTypeError: 'Not map type',
messageKey: "message",
statusCodeKey: "status",
couldNotParseError: "Could not parse error",
jsonIsEmptyError: "JSON is empty",
noInternetError: "No internet connection",
jsonNullError: "JSON is null",
jsonUnsupportedObjectError: "JSON is unsupported object",
notMapTypeError: "Not map type",
};
/// In here NODE_ENV is an environment variable that is set to 'production' or 'development'
/// It may differ according to your project setup
const isTestMode = process.env.NODE_ENV !== 'production';
const isTestMode = process.env.NODE_ENV !== "production";
// Create a new instance of NetworkManager
const networkManagerInstance = new NetworkManager({
baseUrl: 'https://api.example.com', // Production base URL
devBaseUrl: 'https://dev.example.com', // Development base URL
baseUrl: "https://api.example.com", // Production base URL
devBaseUrl: "https://dev.example.com", // Development base URL
testMode: isTestMode, // Test mode: false (production), true (development)
baseOptions: {}, // Axios config options
errorParams: networkErrorParams, // Error parameters
isClientSideWeb: typeof window !== 'undefined' && typeof localStorage !== 'undefined'
isClientSideWeb: typeof window !== "undefined" && typeof localStorage !== "undefined",
});
```

Expand All @@ -86,16 +86,17 @@ future requests.

```typescript
// Set access token
networkManager.setAccessToken('your-access-token');
networkManager.setAccessToken("your-access-token");
// Set refresh token
networkManager.setRefreshToken('your-refresh-token');
networkManager.setRefreshToken("your-refresh-token");
```

## Making Requests:

### Request:

`request` is used to fetch or send data where a single response model is expected.

```typescript
// Example GET request to fetch a single model
const product = await networkManager.request<ProductModel>({
Expand All @@ -104,7 +105,6 @@ const product = await networkManager.request<ProductModel>({
});
/// response.data is of type BookEntity


// Example POST request and get response
const signInResponse = await networkManager.request<SignInResponseDto>({
method: RequestMethod.POST,
Expand Down Expand Up @@ -156,15 +156,13 @@ export interface IAuthRemoteDataSource {
/// src/feature-name/data/datasources/auth-remote-datasource.ts
@injectable()
export class AuthRemoteDataSource implements IAuthRemoteDataSource {
constructor(
@inject('INetworkManager') private networkManager: INetworkManager
) {}
constructor(@inject("INetworkManager") private networkManager: INetworkManager) {}

async signIn(dto: SignInDto): Promise<SignInResponseDto> {
const result = await this.networkManager.request<SignInResponseDto>({
method: 'POST',
method: "POST",
url: `/api/auth/sign-in`,
data: dto
data: dto,
});

this.networkManager.setAccessToken(result.accesToken);
Expand All @@ -181,8 +179,8 @@ network requests.
@injectable()
export class AuthRepository implements IAuthRepository {
constructor(
@inject('IAuthRemoteDataSource') private remoteDataSource: IAuthRemoteDataSource,
@inject('IAuthLocalDataSource') private localDataSource: IAuthLocalDataSource
@inject("IAuthRemoteDataSource") private remoteDataSource: IAuthRemoteDataSource,
@inject("IAuthLocalDataSource") private localDataSource: IAuthLocalDataSource
) {}

async signIn(dto: SignInDto): Promise<void> {
Expand All @@ -194,7 +192,7 @@ export class AuthRepository implements IAuthRepository {
}
}
}
````
```

## Error Handling with ApiException according to the Clean Architecture

Expand All @@ -205,9 +203,7 @@ providing consistent error-handling across your app. Which are caught with a try
/// AuthController.ts
@injectable()
export class AuthController {
constructor(
@inject(SignIn) private signInUseCase: SignIn,
) {}
constructor(@inject(SignIn) private signInUseCase: SignIn) {}

async handleSignIn(dto: SignInDto): Promise<void> {
try {
Expand All @@ -216,7 +212,6 @@ export class AuthController {
throw error;
}
}
}

/// sign-in.tsx
Expand All @@ -225,10 +220,10 @@ const signInController = container.get<AuthController>(AuthController);

const handleSignIn = async () => {
try {
const dto: SignInDto = {email, password};
const dto: SignInDto = { email, password };
setLoading(true);
await signInController.handleSignIn(dto);
router.push('/');
router.push("/");
} catch (err) {
setLoading(false);
setError((err as ApiException).message);
Expand All @@ -249,37 +244,36 @@ Create a module for the network manager using `Inversify`.

```typescript
// network.container.ts
import {ContainerModule, interfaces} from 'inversify';
import {INetworkManager, NetworkManager, NetworkErrorParams} from 'next-netkit';
import { ContainerModule, interfaces } from "inversify";
import { INetworkManager, NetworkManager, NetworkErrorParams } from "next-netkit";

// Define error-handling parameters
const networkErrorParams: NetworkErrorParams = {
messageKey: 'message',
statusCodeKey: 'status',
couldNotParseError: 'Could not parse error',
jsonIsEmptyError: 'JSON is empty',
noInternetError: 'No internet connection',
jsonNullError: 'JSON is null',
jsonUnsupportedObjectError: 'JSON is unsupported object',
notMapTypeError: 'Not map type',
messageKey: "message",
statusCodeKey: "status",
couldNotParseError: "Could not parse error",
jsonIsEmptyError: "JSON is empty",
noInternetError: "No internet connection",
jsonNullError: "JSON is null",
jsonUnsupportedObjectError: "JSON is unsupported object",
notMapTypeError: "Not map type",
};

// Create NetworkManager instance
const networkManagerInstance = new NetworkManager(
'https://api.example.com',
'https://dev.example.com',
false,
{},
networkErrorParams
"https://api.example.com",
"https://dev.example.com",
false,
{},
networkErrorParams
);

// Create a network container module
const networkContainer = new ContainerModule((bind: interfaces.Bind) => {
bind<INetworkManager>('INetworkManager').toConstantValue(networkManagerInstance);
bind<INetworkManager>("INetworkManager").toConstantValue(networkManagerInstance);
});

export {networkContainer};
export { networkContainer };
```

### Merging Containers
Expand All @@ -288,17 +282,17 @@ You can merge multiple containers, including the network container, like so:

```typescript
// main.container.ts
import {Container} from 'inversify';
import {authContainer} from './auth/auth.container';
import {networkContainer} from './network.container';
import { Container } from "inversify";
import { authContainer } from "./auth/auth.container";
import { networkContainer } from "./network.container";

const container = new Container();

// Merge containers
container.load(authContainer);
container.load(networkContainer);

export {container};
export { container };
```

## License
Expand All @@ -309,4 +303,4 @@ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file

- **axios** - MIT License. See [axios repository](https://github.com/axios/axios) for license details.
- **inversify** - MIT License. See [inversify repository](https://github.com/inversify/InversifyJS) for license details.
- **reflect-metadata** - Apache-2.0 License. See [reflect-metadata repository](https://github.com/rbuckton/reflect-metadata) for license details.
- **reflect-metadata** - Apache-2.0 License. See [reflect-metadata repository](https://github.com/rbuckton/reflect-metadata) for license details.
2 changes: 1 addition & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ export { NetworkManager } from "./src/network-manager";
export type { INetworkManager } from "./src/network-manager.interface";
export { NetworkErrorParams } from "./src/interfaces/network-error-params";
export { ApiException } from "./src/error/api-exception";
export { RequestMethod } from "./src/enums/request-method.enum";
export { RequestMethod } from "./src/enums/request-method.enum";
16 changes: 8 additions & 8 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import type { Config } from '@jest/types';
import type { Config } from "@jest/types";

const config: Config.InitialOptions = {
preset: 'ts-jest',
testEnvironment: 'node',
preset: "ts-jest",
testEnvironment: "node",
transform: {
'^.+\\.tsx?$': 'ts-jest',
"^.+\\.tsx?$": "ts-jest",
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
transformIgnorePatterns: ['<rootDir>/node_modules/'],
testMatch: ['<rootDir>/tests/**/*.test.ts'],
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
transformIgnorePatterns: ["<rootDir>/node_modules/"],
testMatch: ["<rootDir>/tests/**/*.test.ts"],
};

export default config;
export default config;
Loading

0 comments on commit 75b2964

Please sign in to comment.