Skip to content

Commit

Permalink
Merge pull request #1 from Diaszano/feature/creationAndImplementation
Browse files Browse the repository at this point in the history
Feature/creation and implementation
  • Loading branch information
Diaszano authored May 14, 2023
2 parents 34fa30f + 84da4a0 commit b460c83
Show file tree
Hide file tree
Showing 6 changed files with 229 additions and 3 deletions.
105 changes: 104 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "linketrack",
"name": "linketrackjs",
"version": "1.0.0",
"description": "Uma interface amigável para a API de rastreamento de encomendas dos Correios desenvolvida pela Link & Track.",
"main": "dist/linketrack.js",
Expand All @@ -24,6 +24,7 @@
"@types/node": "^20.1.4",
"@typescript-eslint/eslint-plugin": "^5.59.5",
"@typescript-eslint/parser": "^5.59.5",
"dotenv": "^16.0.3",
"eslint": "^8.40.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-prettier": "^4.2.1",
Expand All @@ -33,5 +34,8 @@
"vite-tsconfig-paths": "^4.2.0",
"vitest": "^0.31.0",
"vitest-mock-extended": "^1.1.3"
},
"dependencies": {
"axios": "^1.4.0"
}
}
6 changes: 6 additions & 0 deletions src/errors/LinketrackError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default class LinketrackError extends Error {
constructor(message: string) {
super(message);
this.name = 'LinketrackError';
}
}
17 changes: 17 additions & 0 deletions src/interface/LinketrackResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
interface Evento {
data: string;
hora: string;
local: string;
status: string;
subStatus: Array<string>;
}

export default interface LinketrackResponse {
codigo: string;
servico: string;
host: string;
quantidade: number;
eventos: Array<Evento>;
time: number;
ultimo?: string;
}
52 changes: 52 additions & 0 deletions src/linketrack.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import 'dotenv/config';
import { describe, expect, it } from 'vitest';
import Linketrack from './linketrack';
import LinketrackResponse from './interface/LinketrackResponse';

describe('linketrack', async (): Promise<void> => {
it('Deve dar erro de autorização', async (): Promise<void> => {
const linketrack = new Linketrack('user', 'token');
expect(linketrack.track('LX002249507BR')).rejects.toThrow(
'Usuário não autorizado.',
);
});
it('Deve rastrear uma encomenda', async (): Promise<void> => {
const linketrack = new Linketrack(
process.env.LINKETRACK_USER || '',
process.env.LINKETRACK_TOKEN || '',
);

const expectedResponse: Partial<LinketrackResponse> = {
codigo: 'LX002249507BR',
servico: 'PAC - Encomenda Econômica',
quantidade: 0,
eventos: [],
};

expect(linketrack.track('LX002249507BR')).resolves.toMatchObject(
expectedResponse,
);
});
it('Deve rastrear duas encomendas', async (): Promise<void> => {
const linketrack = new Linketrack(
process.env.LINKETRACK_USER || '',
process.env.LINKETRACK_TOKEN || '',
);

const response: Partial<LinketrackResponse> = {
codigo: 'LX002249507BR',
servico: 'PAC - Encomenda Econômica',
quantidade: 0,
eventos: [],
};

const expectedResponse = new Array<Partial<LinketrackResponse>>(
response,
response,
);

expect(
linketrack.trackAll('LX002249507BR', 'LX002249507BR'),
).resolves.toMatchObject(expectedResponse);
});
});
46 changes: 45 additions & 1 deletion src/linketrack.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,46 @@
const oi: string = "Oi pessoal!"
import axios, { AxiosError } from 'axios';
import LinketrackResponse from './interface/LinketrackResponse';
import LinketrackError from './errors/LinketrackError';

export default class linketrack {
constructor(private readonly user: string, private readonly token: string) {}

async track(code: string): Promise<LinketrackResponse> {
return this.request(code);
}

async trackAll(...codes: Array<string>): Promise<Array<LinketrackResponse>> {
const array_track = new Array<LinketrackResponse>();
for (const code of codes) {
array_track.push(await this.request(code));
}
return array_track;
}

private async request(code: string): Promise<LinketrackResponse> {
try {
const response = await axios.get(this.url(code));
return response.data;
} catch (error) {
if (error instanceof AxiosError) {
if (error.code === 'ERR_BAD_REQUEST') {
if (error.response?.statusText === 'Unauthorized') {
throw new LinketrackError('Usuário não autorizado.');
}
if (error.response?.statusText === 'Too Many Requests') {
throw new LinketrackError(
'Muitas solicitações estão sendo feitas.',
);
}
}
}
console.error(error);
throw new LinketrackError((error as Error).message);
}
}

private url(code: string): string {
const url_base = 'https://api.linketrack.com/track/json';
return `${url_base}?user=${this.user}&token=${this.token}&codigo=${code}`;
}
}

0 comments on commit b460c83

Please sign in to comment.