Skip to content

Commit

Permalink
Merge pull request #10 from ChocolateNao/fix/player-numeric
Browse files Browse the repository at this point in the history
Fix/player numeric
  • Loading branch information
ChocolateNao authored Mar 23, 2024
2 parents 4e2e6bb + 5b342d2 commit f30bf25
Show file tree
Hide file tree
Showing 10 changed files with 89 additions and 43 deletions.
6 changes: 3 additions & 3 deletions DOCS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

- [Stratz](#stratz)
- [new Stratz(apiToken)](#new-stratzapitoken)
- [stratz.\_apiReq(path, method, \[queryParameters\]) ⇒ Promise\<any\>](#stratz_apireqpath-method-queryparameters--promiseany)
- [stratz.\_apiReq(path, method, \[queryParameters\]) ⇒ Promise\<(HttpExceptionBody|any)\>](#stratz_apireqpath-method-queryparameters--promisehttpexceptionbodyany)
- [stratz.getAbilities(\[languageId\], \[gameVersionId\]) ⇒ Record\<string, Ability\>](#stratzgetabilitieslanguageid-gameversionid--recordstring-ability)
- [stratz.getGameVersion() ⇒ Promise\<Array\<GameVersion\>\>](#stratzgetgameversion--promisearraygameversion)
- [stratz.getLanguages() ⇒ Promise\<Record\<string, string\>\>](#stratzgetlanguages--promiserecordstring-string)
Expand Down Expand Up @@ -66,11 +66,11 @@ Create a new instance of STRATZ REST API wrapper. This is the first thing you do

<a name="Stratz+_apiReq"></a>

### stratz.\_apiReq(path, method, [queryParameters]) ⇒ <code>Promise&lt;any&gt;</code>
### stratz.\_apiReq(path, method, [queryParameters]) ⇒ <code>Promise&lt;(HttpExceptionBody\|any)&gt;</code>
Create a direct HTTP request to the STRATZ API.

**Kind**: instance method of [<code>Stratz</code>](#Stratz)
**Returns**: <code>Promise&lt;any&gt;</code> - Promise object that resolves with the result object of the HTTPS request.
**Returns**: <code>Promise&lt;(HttpExceptionBody\|any)&gt;</code> - Promise object that resolves with the result object of the HTTPS request OR the error object of type `HttpExceptionBody`.
**Internal**:

| Param | Type | Description |
Expand Down
25 changes: 16 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,19 +125,25 @@ stratz.getPlayerSummary(282424658, { gameMode: 2 }) // in a form of an object
console.log(err);;
});

// Handling queryParameters
stratz.getPlayerSummary(282424658, { gameMode: 2 }) // in a form of an object
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);;
});
// Handling errors. All errors will match the HttpExceptionBody type
try {
const data = await api.getPlayer(121212);
console.log(data);
} catch (error) {
const e = error as HttpExceptionBody;
console.log(e);
}
// {
// isError: true,
// status: 204,
// message: 'No Content',
// description: 'The request was processed but no content was found with given parameters'
// }
```

## Development

First of all, clone the repository and install dev-dependencies with `npm install` (or `pnpm add` or `yarn add`). To run tests, you will need an API key:
First of all, clone the repository and install dev-dependencies with `npm install` (or `pnpm install` or `yarn install`). To run tests, you will need an API key:

```bash
# copy and edit the .env file
Expand All @@ -151,6 +157,7 @@ npm run test
## Building

You can create a production version of the library with the following command.

*Note: This will also create a new documentation file.*

```bash
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "stratz.js",
"version": "2.2.1",
"version": "2.2.2",
"description": "A Node.js STRATZ REST API wrapper",
"main": "./lib/index.js",
"module": "./lib/index.mjs",
Expand Down
29 changes: 17 additions & 12 deletions src/Stratz.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import type { IncomingMessage } from 'node:http';
import https from 'node:https';
import type { ParsedUrlQueryInput } from 'querystring';
import querystring from 'querystring';
import type { ParsedUrlQueryInput } from 'node:querystring';
import querystring from 'node:querystring';

import { StratzLanguage } from './enums/StratzLanguage.enum';
import { HttpException } from './exceptions/http.exception';
import type { Ability } from './models/Ability.interface';
import type { Cluster } from './models/Cluster.interface';
import type { AbilityList, HeroList } from './models/DataList.interface';
Expand Down Expand Up @@ -67,7 +68,7 @@ class Stratz {
* @param {string} path - Endpoint path.
* @param {string} method - HTTPS method.
* @param {*} [queryParameters] - Query parameters for the request.
* @return {Promise<any>} Promise object that resolves with the result object of the HTTPS request.
* @return {Promise<HttpExceptionBody | any>} Promise object that resolves with the result object of the HTTPS request OR the error object of type `HttpExceptionBody`.
*/
private async _apiReq(
path: string,
Expand Down Expand Up @@ -105,28 +106,32 @@ class Stratz {

response.on('end', () => {
if (response.statusCode === 302) {
resolve({ status: 'Found' });
resolve({ statusCode: response.statusCode, message: 'Found' });
}
if (response.statusCode === 204) {
reject(
new HttpException(
response.statusCode,
'No Content',
'The request was processed but no content was found with given parameters',
).initBody(),
);
}
if (
response.statusCode &&
response.statusCode !== 204 &&
response.statusCode >= 200 &&
response.statusCode < 300
) {
resolve(JSON.parse(data));
} else {
reject(
new Error(
`HTTPS request failed with status code ${response.statusCode}`,
),
);
reject(new HttpException(response.statusCode ?? 500).initBody());
}
});

response.on('error', (error: string) => {
reject(
new Error(
`HTTPS request failed with status code ${response.statusCode} with an error: ${error}`,
),
new HttpException(response.statusCode ?? 500, error).initBody(),
);
});
})
Expand Down
30 changes: 30 additions & 0 deletions src/exceptions/http.exception.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export interface HttpExceptionBody {
isError: boolean;
status: number;
message?: string;
description?: string;
}

export class HttpException extends Error {
public readonly status?: number;
public readonly message: string = 'Unhandled exception';
public readonly description?: string;

constructor(statusCode: number, msg?: string, description?: string) {
super();
this.status = statusCode;
if (msg) this.message = msg;
this.description = description;

this.initBody();
}

public initBody(): HttpExceptionBody {
return {
isError: true,
status: this.status ?? 500,
message: this.message,
description: this?.description,
};
}
}
8 changes: 4 additions & 4 deletions src/models/Ability.interface.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
export interface Ability {
id: number;
name?: string;
language: Language;
stat?: Stat;
language: AbilityLanguage;
stat?: AbilityStat;
isTalent: boolean;
uri?: string;
}

interface Language {
interface AbilityLanguage {
abilityId: number;
gameVersionId: number;
languageId: number;
Expand All @@ -20,7 +20,7 @@ interface Language {
aghanimDescription?: string;
}

interface Stat {
interface AbilityStat {
abilityId: number;
gameVersionId: number;
type: number;
Expand Down
12 changes: 6 additions & 6 deletions src/models/Hero.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,21 @@ export interface Hero {
id: number;
name: string;
shortName: string;
stat: Stat;
stat: HeroStat;
aliases: string[];
displayName?: string;
abilities?: Ability[];
abilities?: HeroAbility[];
roles?: Role[];
talents?: Talent[];
language?: Language;
language?: HeroLanguage;
}

interface Ability {
interface HeroAbility {
slot: number;
abilityId: number;
}

interface Language {
interface HeroLanguage {
heroId: number;
gameVersionId: number;
languageId: number;
Expand All @@ -30,7 +30,7 @@ interface Role {
level: number;
}

interface Stat {
interface HeroStat {
gameVersionId: number;
enabled?: boolean;
heroUnlockOrder?: number;
Expand Down
8 changes: 4 additions & 4 deletions src/models/Item.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ export interface Item {
name: string;
displayName?: string;
shortName: string;
language: Language;
stat?: Stat;
language: ItemLanguage;
stat?: ItemStat;
image?: string;
isInNeuralNetwork: boolean;
isFullItemHeroPurchaseItem: boolean;
Expand All @@ -17,15 +17,15 @@ interface Component {
componentId: number;
}

interface Language {
interface ItemLanguage {
displayName: string;
lore: string[];
description: string[];
notes: string[];
attributes: string[];
}

interface Stat {
interface ItemStat {
behavior: number;
unitTargetType: number;
unitTargetTeam: number;
Expand Down
8 changes: 6 additions & 2 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,15 @@ describe('Stratz.js Unit Tests', () => {
expect(result).toBeDefined();
});

test('Get Player', async () => {
test('Get Player with Valid ID', async () => {
const result = await api.getPlayer(STEAM_ID);
expect(result).toBeDefined();
});

test('Get Player with Invalid ID', async () => {
expect(async () => await api.getPlayer(121212)).rejects.toHaveProperty('isError', true);
});

test('Get Player Basic Info', async () => {
const result = await api.getPlayerBasic(STEAM_ID);
expect(result).toBeDefined();
Expand Down Expand Up @@ -135,7 +139,7 @@ describe('Stratz.js Unit Tests', () => {
});

test('Get Played With Pro', async () => {
await expect(async () => await api.getPlayedWithPro(STEAM_ID)).rejects.toThrow();
await expect(async () => await api.getPlayedWithPro(STEAM_ID)).rejects.toHaveProperty('isError', true);
});

test('Get Player Summary', async () => {
Expand Down

0 comments on commit f30bf25

Please sign in to comment.