@sargonpiraev/hh-api-client 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,261 @@
1
+ # HeadHunter API Client
2
+
3
+ A TypeScript client for the HeadHunter API, generated from the official OpenAPI specification.
4
+
5
+ ## Features
6
+
7
+ - 🔥 **TypeScript first** - Full type safety with generated types
8
+ - 🚀 **Modern SDK** - Built with `@hey-api/openapi-ts`
9
+ - 📝 **Complete API coverage** - All HeadHunter API endpoints
10
+ - 🛡️ **Built-in validation** - Request/response validation
11
+ - 🎯 **Tree-shakeable** - Import only what you need
12
+ - 📚 **Well documented** - JSDoc comments for all methods
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install hh-api-client
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ```typescript
23
+ import { createHeadHunterClient, getVacancies, getAreas, type GetVacanciesData } from 'hh-api-client'
24
+
25
+ // Create a configured client
26
+ const client = createHeadHunterClient({
27
+ userAgent: 'MyApp/1.0.0 (contact@example.com)',
28
+ accessToken: 'your-access-token', // optional
29
+ })
30
+
31
+ // Search for vacancies
32
+ const searchParams: GetVacanciesData = {
33
+ query: {
34
+ text: 'JavaScript developer',
35
+ area: '1', // Moscow
36
+ per_page: 50,
37
+ },
38
+ }
39
+
40
+ const vacancies = await getVacancies({
41
+ client,
42
+ ...searchParams,
43
+ })
44
+
45
+ console.log(`Found ${vacancies.data.found} vacancies`)
46
+
47
+ // Get dictionaries
48
+ const areas = await getAreas({ client })
49
+ console.log('Available areas:', areas.data)
50
+ ```
51
+
52
+ ## Usage Examples
53
+
54
+ ### Search Vacancies
55
+
56
+ ```typescript
57
+ import { getVacancies, type GetVacanciesData } from 'hh-api-client'
58
+
59
+ const searchParams: GetVacanciesData = {
60
+ query: {
61
+ text: 'Frontend Developer',
62
+ area: '1', // Moscow
63
+ professional_role: '96', // Developer role
64
+ experience: 'between1And3',
65
+ employment: 'full',
66
+ schedule: 'remote',
67
+ salary_from: 100000,
68
+ currency: 'RUR',
69
+ only_with_salary: true,
70
+ },
71
+ }
72
+
73
+ const result = await getVacancies({ client, ...searchParams })
74
+ ```
75
+
76
+ ### Get Vacancy Details
77
+
78
+ ```typescript
79
+ import { getVacancy } from 'hh-api-client'
80
+
81
+ const vacancy = await getVacancy({
82
+ client,
83
+ path: { vacancy_id: '12345' },
84
+ })
85
+
86
+ console.log(vacancy.data.name)
87
+ console.log(vacancy.data.description)
88
+ ```
89
+
90
+ ### Apply to Vacancy
91
+
92
+ ```typescript
93
+ import { applyToVacancy } from 'hh-api-client'
94
+
95
+ await applyToVacancy({
96
+ client,
97
+ path: { vacancy_id: '12345' },
98
+ body: {
99
+ resume_id: 'resume-id',
100
+ message: 'I am interested in this position...',
101
+ },
102
+ })
103
+ ```
104
+
105
+ ### Work with Dictionaries
106
+
107
+ ```typescript
108
+ import { getAreas, getIndustries, getSkills, getProfessionalRolesDictionary } from 'hh-api-client'
109
+
110
+ // Get all areas (cities/regions)
111
+ const areas = await getAreas({ client })
112
+
113
+ // Get industries
114
+ const industries = await getIndustries({ client })
115
+
116
+ // Get skills
117
+ const skills = await getSkills({ client })
118
+
119
+ // Get professional roles
120
+ const roles = await getProfessionalRolesDictionary({ client })
121
+ ```
122
+
123
+ ### User Information
124
+
125
+ ```typescript
126
+ import { getCurrentUserInfo, editCurrentUserInfo } from 'hh-api-client'
127
+
128
+ // Get current user info
129
+ const user = await getCurrentUserInfo({ client })
130
+
131
+ // Update user info
132
+ await editCurrentUserInfo({
133
+ client,
134
+ body: {
135
+ first_name: 'John',
136
+ last_name: 'Doe',
137
+ email: 'john.doe@example.com',
138
+ },
139
+ })
140
+ ```
141
+
142
+ ## Configuration
143
+
144
+ ### Required User-Agent
145
+
146
+ HeadHunter API requires a specific User-Agent format:
147
+
148
+ ```
149
+ ApplicationName/Version (contact@example.com)
150
+ ```
151
+
152
+ Example:
153
+
154
+ ```typescript
155
+ const client = createHeadHunterClient({
156
+ userAgent: 'JobSearchApp/1.0.0 (support@jobsearch.com)',
157
+ })
158
+ ```
159
+
160
+ ### Authentication
161
+
162
+ For protected endpoints, provide an access token:
163
+
164
+ ```typescript
165
+ const client = createHeadHunterClient({
166
+ userAgent: 'MyApp/1.0.0 (contact@example.com)',
167
+ accessToken: 'your-oauth-token',
168
+ })
169
+ ```
170
+
171
+ ### Custom Base URL
172
+
173
+ For testing or custom environments:
174
+
175
+ ```typescript
176
+ const client = createHeadHunterClient({
177
+ userAgent: 'MyApp/1.0.0 (contact@example.com)',
178
+ baseURL: 'https://api.hh.ru', // default
179
+ })
180
+ ```
181
+
182
+ ## API Reference
183
+
184
+ ### Most Used Functions
185
+
186
+ - `getVacancies()` - Search vacancies
187
+ - `getVacancy()` - Get vacancy details
188
+ - `getAreas()` - Get areas/cities
189
+ - `getIndustries()` - Get industries
190
+ - `getCurrentUserInfo()` - Get user info
191
+ - `applyToVacancy()` - Apply to vacancy
192
+
193
+ ### All Available Functions
194
+
195
+ The client exports all generated SDK functions. See the [HeadHunter API documentation](https://api.hh.ru/openapi/redoc) for complete reference.
196
+
197
+ ```typescript
198
+ // Import everything
199
+ import * as HHApi from 'hh-api-client'
200
+
201
+ // Or import specific functions
202
+ import {
203
+ getVacancies,
204
+ getNegotiations,
205
+ createResume,
206
+ // ... etc
207
+ } from 'hh-api-client'
208
+ ```
209
+
210
+ ## TypeScript Support
211
+
212
+ Full TypeScript support with generated types:
213
+
214
+ ```typescript
215
+ import type { GetVacanciesData, GetVacanciesResponses, Vacancy, Area, Industry } from 'hh-api-client'
216
+
217
+ const handleVacancy = (vacancy: Vacancy) => {
218
+ console.log(vacancy.name)
219
+ console.log(vacancy.salary?.from)
220
+ }
221
+ ```
222
+
223
+ ## Error Handling
224
+
225
+ ```typescript
226
+ try {
227
+ const result = await getVacancies({ client, query: { text: 'Developer' } })
228
+ console.log(result.data)
229
+ } catch (error) {
230
+ if (error.status === 400) {
231
+ console.error('Bad request:', error.data)
232
+ } else if (error.status === 403) {
233
+ console.error('Forbidden:', error.data)
234
+ } else {
235
+ console.error('Unexpected error:', error)
236
+ }
237
+ }
238
+ ```
239
+
240
+ ## Development
241
+
242
+ ```bash
243
+ # Install dependencies
244
+ npm install
245
+
246
+ # Generate types from OpenAPI spec
247
+ npm run openapi-ts
248
+
249
+ # Build
250
+ npm run build
251
+
252
+ # Test
253
+ npm run test
254
+
255
+ # Lint
256
+ npm run lint
257
+ ```
258
+
259
+ ## License
260
+
261
+ MIT
@@ -0,0 +1,2 @@
1
+ import type { Client, Config } from './types.js';
2
+ export declare const createClient: (config?: Config) => Client;
@@ -0,0 +1,143 @@
1
+ import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.js';
2
+ export const createClient = (config = {}) => {
3
+ let _config = mergeConfigs(createConfig(), config);
4
+ const getConfig = () => ({ ..._config });
5
+ const setConfig = (config) => {
6
+ _config = mergeConfigs(_config, config);
7
+ return getConfig();
8
+ };
9
+ const interceptors = createInterceptors();
10
+ const request = async (options) => {
11
+ const opts = {
12
+ ..._config,
13
+ ...options,
14
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
15
+ headers: mergeHeaders(_config.headers, options.headers),
16
+ };
17
+ if (opts.security) {
18
+ await setAuthParams({
19
+ ...opts,
20
+ security: opts.security,
21
+ });
22
+ }
23
+ if (opts.requestValidator) {
24
+ await opts.requestValidator(opts);
25
+ }
26
+ if (opts.body && opts.bodySerializer) {
27
+ opts.body = opts.bodySerializer(opts.body);
28
+ }
29
+ // remove Content-Type header if body is empty to avoid sending invalid requests
30
+ if (opts.body === undefined || opts.body === '') {
31
+ opts.headers.delete('Content-Type');
32
+ }
33
+ const url = buildUrl(opts);
34
+ const requestInit = {
35
+ redirect: 'follow',
36
+ ...opts,
37
+ };
38
+ let request = new Request(url, requestInit);
39
+ for (const fn of interceptors.request._fns) {
40
+ if (fn) {
41
+ request = await fn(request, opts);
42
+ }
43
+ }
44
+ // fetch must be assigned here, otherwise it would throw the error:
45
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
46
+ const _fetch = opts.fetch;
47
+ let response = await _fetch(request);
48
+ for (const fn of interceptors.response._fns) {
49
+ if (fn) {
50
+ response = await fn(response, request, opts);
51
+ }
52
+ }
53
+ const result = {
54
+ request,
55
+ response,
56
+ };
57
+ if (response.ok) {
58
+ if (response.status === 204 ||
59
+ response.headers.get('Content-Length') === '0') {
60
+ return opts.responseStyle === 'data'
61
+ ? {}
62
+ : {
63
+ data: {},
64
+ ...result,
65
+ };
66
+ }
67
+ const parseAs = (opts.parseAs === 'auto'
68
+ ? getParseAs(response.headers.get('Content-Type'))
69
+ : opts.parseAs) ?? 'json';
70
+ let data;
71
+ switch (parseAs) {
72
+ case 'arrayBuffer':
73
+ case 'blob':
74
+ case 'formData':
75
+ case 'json':
76
+ case 'text':
77
+ data = await response[parseAs]();
78
+ break;
79
+ case 'stream':
80
+ return opts.responseStyle === 'data'
81
+ ? response.body
82
+ : {
83
+ data: response.body,
84
+ ...result,
85
+ };
86
+ }
87
+ if (parseAs === 'json') {
88
+ if (opts.responseValidator) {
89
+ await opts.responseValidator(data);
90
+ }
91
+ if (opts.responseTransformer) {
92
+ data = await opts.responseTransformer(data);
93
+ }
94
+ }
95
+ return opts.responseStyle === 'data'
96
+ ? data
97
+ : {
98
+ data,
99
+ ...result,
100
+ };
101
+ }
102
+ let error = await response.text();
103
+ try {
104
+ error = JSON.parse(error);
105
+ }
106
+ catch {
107
+ // noop
108
+ }
109
+ let finalError = error;
110
+ for (const fn of interceptors.error._fns) {
111
+ if (fn) {
112
+ finalError = (await fn(error, response, request, opts));
113
+ }
114
+ }
115
+ finalError = finalError || {};
116
+ if (opts.throwOnError) {
117
+ throw finalError;
118
+ }
119
+ // TODO: we probably want to return error and improve types
120
+ return opts.responseStyle === 'data'
121
+ ? undefined
122
+ : {
123
+ error: finalError,
124
+ ...result,
125
+ };
126
+ };
127
+ return {
128
+ buildUrl,
129
+ connect: (options) => request({ ...options, method: 'CONNECT' }),
130
+ delete: (options) => request({ ...options, method: 'DELETE' }),
131
+ get: (options) => request({ ...options, method: 'GET' }),
132
+ getConfig,
133
+ head: (options) => request({ ...options, method: 'HEAD' }),
134
+ interceptors,
135
+ options: (options) => request({ ...options, method: 'OPTIONS' }),
136
+ patch: (options) => request({ ...options, method: 'PATCH' }),
137
+ post: (options) => request({ ...options, method: 'POST' }),
138
+ put: (options) => request({ ...options, method: 'PUT' }),
139
+ request,
140
+ setConfig,
141
+ trace: (options) => request({ ...options, method: 'TRACE' }),
142
+ };
143
+ };
@@ -0,0 +1,7 @@
1
+ export type { Auth } from '../core/auth.js';
2
+ export type { QuerySerializerOptions } from '../core/bodySerializer.js';
3
+ export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.js';
4
+ export { buildClientParams } from '../core/params.js';
5
+ export { createClient } from './client.js';
6
+ export type { Client, ClientOptions, Config, CreateClientConfig, Options, OptionsLegacyParser, RequestOptions, RequestResult, ResponseStyle, TDataShape, } from './types.js';
7
+ export { createConfig, mergeHeaders } from './utils.js';
@@ -0,0 +1,4 @@
1
+ export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.js';
2
+ export { buildClientParams } from '../core/params.js';
3
+ export { createClient } from './client.js';
4
+ export { createConfig, mergeHeaders } from './utils.js';
@@ -0,0 +1,119 @@
1
+ import type { Auth } from '../core/auth.js';
2
+ import type { Client as CoreClient, Config as CoreConfig } from '../core/types.js';
3
+ import type { Middleware } from './utils.js';
4
+ export type ResponseStyle = 'data' | 'fields';
5
+ export interface Config<T extends ClientOptions = ClientOptions> extends Omit<RequestInit, 'body' | 'headers' | 'method'>, CoreConfig {
6
+ /**
7
+ * Base URL for all requests made by this client.
8
+ */
9
+ baseUrl?: T['baseUrl'];
10
+ /**
11
+ * Fetch API implementation. You can use this option to provide a custom
12
+ * fetch instance.
13
+ *
14
+ * @default globalThis.fetch
15
+ */
16
+ fetch?: (request: Request) => ReturnType<typeof fetch>;
17
+ /**
18
+ * Please don't use the Fetch client for Next.js applications. The `next`
19
+ * options won't have any effect.
20
+ *
21
+ * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
22
+ */
23
+ next?: never;
24
+ /**
25
+ * Return the response data parsed in a specified format. By default, `auto`
26
+ * will infer the appropriate method from the `Content-Type` response header.
27
+ * You can override this behavior with any of the {@link Body} methods.
28
+ * Select `stream` if you don't want to parse response data at all.
29
+ *
30
+ * @default 'auto'
31
+ */
32
+ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text';
33
+ /**
34
+ * Should we return only data or multiple fields (data, error, response, etc.)?
35
+ *
36
+ * @default 'fields'
37
+ */
38
+ responseStyle?: ResponseStyle;
39
+ /**
40
+ * Throw an error instead of returning it in the response?
41
+ *
42
+ * @default false
43
+ */
44
+ throwOnError?: T['throwOnError'];
45
+ }
46
+ export interface RequestOptions<TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string> extends Config<{
47
+ responseStyle: TResponseStyle;
48
+ throwOnError: ThrowOnError;
49
+ }> {
50
+ /**
51
+ * Any body that you want to add to your request.
52
+ *
53
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
54
+ */
55
+ body?: unknown;
56
+ path?: Record<string, unknown>;
57
+ query?: Record<string, unknown>;
58
+ /**
59
+ * Security mechanism(s) to use for the request.
60
+ */
61
+ security?: ReadonlyArray<Auth>;
62
+ url: Url;
63
+ }
64
+ export type RequestResult<TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields'> = ThrowOnError extends true ? Promise<TResponseStyle extends 'data' ? TData extends Record<string, unknown> ? TData[keyof TData] : TData : {
65
+ data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
66
+ request: Request;
67
+ response: Response;
68
+ }> : Promise<TResponseStyle extends 'data' ? (TData extends Record<string, unknown> ? TData[keyof TData] : TData) | undefined : ({
69
+ data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
70
+ error: undefined;
71
+ } | {
72
+ data: undefined;
73
+ error: TError extends Record<string, unknown> ? TError[keyof TError] : TError;
74
+ }) & {
75
+ request: Request;
76
+ response: Response;
77
+ }>;
78
+ export interface ClientOptions {
79
+ baseUrl?: string;
80
+ responseStyle?: ResponseStyle;
81
+ throwOnError?: boolean;
82
+ }
83
+ type MethodFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, 'method'>) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
84
+ type RequestFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, 'method'> & Pick<Required<RequestOptions<TResponseStyle, ThrowOnError>>, 'method'>) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
85
+ type BuildUrlFn = <TData extends {
86
+ body?: unknown;
87
+ path?: Record<string, unknown>;
88
+ query?: Record<string, unknown>;
89
+ url: string;
90
+ }>(options: Pick<TData, 'url'> & Options<TData>) => string;
91
+ export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
92
+ interceptors: Middleware<Request, Response, unknown, RequestOptions>;
93
+ };
94
+ /**
95
+ * The `createClientConfig()` function will be called on client initialization
96
+ * and the returned object will become the client's initial configuration.
97
+ *
98
+ * You may want to initialize your client this way instead of calling
99
+ * `setConfig()`. This is useful for example if you're using Next.js
100
+ * to ensure your client always has the correct values.
101
+ */
102
+ export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
103
+ export interface TDataShape {
104
+ body?: unknown;
105
+ headers?: unknown;
106
+ path?: unknown;
107
+ query?: unknown;
108
+ url: string;
109
+ }
110
+ type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
111
+ export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields'> = OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'body' | 'path' | 'query' | 'url'> & Omit<TData, 'url'>;
112
+ export type OptionsLegacyParser<TData = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields'> = TData extends {
113
+ body?: any;
114
+ } ? TData extends {
115
+ headers?: any;
116
+ } ? OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'body' | 'headers' | 'url'> & TData : OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'body' | 'url'> & TData & Pick<RequestOptions<TResponseStyle, ThrowOnError>, 'headers'> : TData extends {
117
+ headers?: any;
118
+ } ? OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'headers' | 'url'> & TData & Pick<RequestOptions<TResponseStyle, ThrowOnError>, 'body'> : OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'url'> & TData;
119
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,45 @@
1
+ import type { QuerySerializer, QuerySerializerOptions } from '../core/bodySerializer.js';
2
+ import type { Client, ClientOptions, Config, RequestOptions } from './types.js';
3
+ export declare const createQuerySerializer: <T = unknown>({ allowReserved, array, object, }?: QuerySerializerOptions) => (queryParams: T) => string;
4
+ /**
5
+ * Infers parseAs value from provided Content-Type header.
6
+ */
7
+ export declare const getParseAs: (contentType: string | null) => Exclude<Config["parseAs"], "auto">;
8
+ export declare const setAuthParams: ({ security, ...options }: Pick<Required<RequestOptions>, "security"> & Pick<RequestOptions, "auth" | "query"> & {
9
+ headers: Headers;
10
+ }) => Promise<void>;
11
+ export declare const buildUrl: Client['buildUrl'];
12
+ export declare const getUrl: ({ baseUrl, path, query, querySerializer, url: _url, }: {
13
+ baseUrl?: string;
14
+ path?: Record<string, unknown>;
15
+ query?: Record<string, unknown>;
16
+ querySerializer: QuerySerializer;
17
+ url: string;
18
+ }) => string;
19
+ export declare const mergeConfigs: (a: Config, b: Config) => Config;
20
+ export declare const mergeHeaders: (...headers: Array<Required<Config>["headers"] | undefined>) => Headers;
21
+ type ErrInterceptor<Err, Res, Req, Options> = (error: Err, response: Res, request: Req, options: Options) => Err | Promise<Err>;
22
+ type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;
23
+ type ResInterceptor<Res, Req, Options> = (response: Res, request: Req, options: Options) => Res | Promise<Res>;
24
+ declare class Interceptors<Interceptor> {
25
+ _fns: (Interceptor | null)[];
26
+ constructor();
27
+ clear(): void;
28
+ getInterceptorIndex(id: number | Interceptor): number;
29
+ exists(id: number | Interceptor): boolean;
30
+ eject(id: number | Interceptor): void;
31
+ update(id: number | Interceptor, fn: Interceptor): number | false | Interceptor;
32
+ use(fn: Interceptor): number;
33
+ }
34
+ export interface Middleware<Req, Res, Err, Options> {
35
+ error: Pick<Interceptors<ErrInterceptor<Err, Res, Req, Options>>, 'eject' | 'use'>;
36
+ request: Pick<Interceptors<ReqInterceptor<Req, Options>>, 'eject' | 'use'>;
37
+ response: Pick<Interceptors<ResInterceptor<Res, Req, Options>>, 'eject' | 'use'>;
38
+ }
39
+ export declare const createInterceptors: <Req, Res, Err, Options>() => {
40
+ error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
41
+ request: Interceptors<ReqInterceptor<Req, Options>>;
42
+ response: Interceptors<ResInterceptor<Res, Req, Options>>;
43
+ };
44
+ export declare const createConfig: <T extends ClientOptions = ClientOptions>(override?: Config<Omit<ClientOptions, keyof T> & T>) => Config<Omit<ClientOptions, keyof T> & T>;
45
+ export {};