open-index/open-npm huggingface dataset:
npm package: @http-ext/plugin-auth
Description: > A auth plugin for [HttpExt](https://github.com/jscutlery/http-ext).
Latest version: 2.1.1

# @http-ext/plugin-auth

> A auth plugin for [HttpExt](https://github.com/jscutlery/http-ext).

This plugin takes care of handling authorization by:

- adding the `Authorization` header with the given token automatically for each request matching a custom condition,
- triggering a custom token expiration logic on `401 Unauthorized` http responses.

This plugins helps avoiding all the http interceptor boilerplate required to add the authorization token and detect token expiration.

Using matchers like `matchOrigin`, we'll ensure that the token is sent to the right API.
This also helps using different tokens for different APIs in the same app.

## Requirements

The plugin requires `@http-ext/core` and `@http-ext/angular` to be installed.

## Installation

```bash
yarn add @http-ext/plugin-cache @http-ext/core
```

or

```bash
npm install @http-ext/plugin-cache @http-ext/core
```

## Usage

```ts
import { HttpExtModule } from '@http-ext/angular';
import { createAuthPlugin } from '@http-ext/plugin-auth';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    HttpExtModule.forRoot({
      deps: [AuthService],
      config: (authService: AuthService) =>
        createAuthPlugin({
          shouldHandleRequest: matchOrigin('https://secure-origin.com'),
          token: authService.getToken(), // Returns an Observable<string>.
          onUnauthorized: () => authService.markTokenExpired(),
        }),
    }),
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}
```

### Available options

You can give a partial configuration object it will be merged with default values.

| Property              | Type                 | Required | Default value | Description                                                                                  |
| --------------------- | -------------------- | -------- | ------------- | -------------------------------------------------------------------------------------------- |
| `token`               | `Observable<string>` | Yes      | `undefined`   | The bearer token that will be added to every matching request in the `Authorization` header. |
| `onUnauthorized`      | `OnUnauthorized`     | No       | `undefined`   | A function executed when an unauthorized response is thrown.                                 |
| `shouldHandleRequest` | `RequestCondition`   | No       | `undefined`   | Predicate function to know which request the plugin should handle.                           |

To know more about the `shouldHandleRequest` property check-out the [conditional handling section](https://github.com/jscutlery/http-ext#conditional-handling).
npm package: @http-ext/plugin-retry
Description: > A retry plugin for [HttpExt](https://github.com/jscutlery/http-ext).
Latest version: 2.1.1

# @http-ext/plugin-retry

> A retry plugin for [HttpExt](https://github.com/jscutlery/http-ext).

This plugin retries failed network requests using a configurable back-off strategy.

## Requirements

The plugin requires `@http-ext/core` and `@http-ext/angular` to be installed.

## Installation

```bash
yarn add @http-ext/plugin-retry
```

or

```bash
npm install @http-ext/plugin-retry
```

## Usage

The whole configuration object is optional.

```ts
import { HttpExtModule } from '@http-ext/angular';
import { createRetryPlugin } from '@http-ext/plugin-retry';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    HttpExtModule.forRoot({
      plugins: [createRetryPlugin()]
    })
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
```

### Available options

You can give a partial configuration object it will be merged with default values.

| Property              | Type               | Default value            | Description                                                        |
| --------------------- | ------------------ | ------------------------ | ------------------------------------------------------------------ |
| `initialIntervalMs`   | `number`           | `300`                    | Duration before the first retry.                                   |
| `maxIntervalMs`       | `number`           | `10_000`                 | Maximum time span before retrying.                                 |
| `maxRetries`          | `number`           | `3`                      | Maximum number of retries.                                         |
| `shouldRetry`         | `RetryPredicate`   | `isServerOrUnknownError` | Predicate function to know which failed request should be retried. |
| `shouldHandleRequest` | `RequestCondition` | `() => true`             | Predicate function to know which request the plugin should handle. |

Here is an example passing a configuration object.

Keep in mind that HTTP error is not emitted while the plugin is retrying. In the following example the HTTP error will be emitted after 10 retries, then the observable completes.

```ts
import { MemoryStorage } from '@http-ext/plugin-cache';

@NgModule({
  imports: [
    HttpExtModule.forRoot({
      plugins: [
        createRetryPlugin({
          initialIntervalMs: 500,
          maxIntervalMs: 20_000,
          maxRetries: 10,
          shouldRetry: response => response.status !== 404,
          shouldHandleRequest: ({ request }) =>
            request.url.includes('api.github.com')
        })
      ]
    })
  ]
})
export class AppModule {}
```
npm package: @http-query/core
Description: This project contain the http query pattern to filter data in backend by url.
Latest version: 1.0.2

## Http Query

This project contain the http query pattern to filter data in backend by url.

Features:

- Search
- Pagination
- Sorting
- Limit by page
- Get filter from url
- Relations with TypeORM pattern (array)
- Operators contract

## Databases Support

- MySQL

## Coming soon

Features:

- Relations to prisma pattern (objects with includes)

Support:

- Postgres Database
- Mongodb Database
- Redis Database
- SQL Server Database
- Oracle Database

## Installation

NPM:

```bash
npm install @http-query/core
```

yarn:

```bash
yarn add @http-query/core
```

Now implement the `bind` and `getAlias` code in your repository.

## Sample bind method for typeorm

```ts
private bind({ query, relations }: IFind) {
  const order = {};

  query.sort.forEach((item) => {
    order[item.property] = item.order;
  });

  const rules = {
    AND: (qb: SelectQueryBuilder<Entity>, whereQuery: string) => {
      qb.andWhere(whereQuery);
    },
    OR: (qb: SelectQueryBuilder<Entity>, whereQuery: string) => {
      qb.orWhere(whereQuery);
    },
  };

  const where = (qb: SelectQueryBuilder<Entity>) => {
    query.q.forEach((item) => {
      const parsedEntity = this.getAlias(item.entity);
      const property = `${parsedEntity}.${item.property}`;
      const operator = operators[item.operator];
      const value =
        item.operator === 'LIKE' ? `'%${item.value}%'` : `'${item.value}'`;

      rules[item.rule](qb, `${property} ${operator} ${value}`);
    });
  };

  return {
    relations,
    take: query.limit,
    skip: (query.page - 1) * query.limit,
    order,
    where,
  };
}
```

## Sample getAlias method for typeorm

```ts
private getAlias(entity: string): string {
  const { targetName } = this.orm.metadata;

  const parsedEntity = entity.replace(/\w{1}/, (match) =>
    match.toUpperCase(),
  );

  if (parsedEntity === targetName) return parsedEntity;

  return `${targetName}__${entity}`;
}
```
npm package: @http-rpc/client
Description: HTTP RPC Client
Author: LacheRo`
Latest version: 0.5.2

# HTTP RPC Client

## Documentation

Full documentation can be found [here](https://lacherogwu.github.io/http-rpc/).

## Installation

```bash
npm i @http-rpc/client superjson
```

## Usage

`./rpcClient.ts`

```typescript
import superjson from 'superjson';
import { createClient } from '@http-rpc/client';
import type { Router } from '../server/rpc/router';

export const client = createClient<Router>({
	url: 'http://localhost:3000/rpc',
	transformer: superjson,
	async headers() {
		const token = await getToken();

		return {
			Authorization: `Bearer ${token}`,
		};
	},
	/* Optional hooks */
	onRequest(req) {
		console.log(`${req.method?.toUpperCase() ?? 'Unknown'} ${req.url}`);
		return req;
	},
	onResponse(res) {
		console.log(`${res.status} ${res.statusText}`);
		return res;
	},
	onError(err) {
		console.error(err);
		return err;
	},
});
```

```typescript
import { client } from './rpcClient';

const version = await client.version.get();
//    ^? { version: string }

const orders = await client.orders.list({ fields: ['id', 'amount'] });
//    ^? { id: number, amount: number }[]
```
npm package: @http-rpc/server
Description: HTTP RPC Server
Author: LacheRo`
Latest version: 0.5.2

# HTTP RPC Server

## Documentation

Full documentation can be found [here](https://lacherogwu.github.io/http-rpc/).

## Installation

```bash
npm i @http-rpc/server zod fastify superjson
```

## Usage

`./app.ts`

```typescript
import { fastifyRPCPlugin } from '@http-rpc/server/adapters/fastify';
import superjson from 'superjson';
import { router } from './rpc/router';

fastify.register(fastifyRPCPlugin, {
	prefix: '/rpc',
	router,
	transformer: superjson,
});
```

`./router.ts`

```typescript
import { createRoute, RPCError } from '@http-rpc/server';
import { FastifyContext } from '@http-rpc/server/adapters/fastify';
import { z } from 'zod';

const publicRoute = createRoute<FastifyContext>();
const authenticatedRoute = publicRoute.middleware(ctx => {
	const { authorization } = ctx.req.headers;
	const user = await prisma.user.findUnique({
		where: { token: authorization },
	});
	if (!user) throw new RPCError({ code: 'UNAUTHORIZED' });

	return {
		userId: user.id,
	};
});

export const router = {
	version: publicRoute
		.output(
			z.object({
				version: z.string(),
			}),
		)
		.get(() => ({ version: '1.0.0' })),
	orders: {
		list: authenticatedRoute
			.input(z.object({ fields: z.array(z.string()) }))
			.output(z.array(z.object({ id: z.number(), amount: z.number() })))
			.get(ctx => {
				const { userId } = ctx;
				const { fields } = ctx.input;
				return await prisma.order.findMany({
					where: {
						userId,
					},
					select: Object.keys(fields).reduce((acc, field) => {
						acc[field] = true;
						return acc;
					}, {}),
				});
			}),
	},
};

export type Router = typeof router;
```
npm package: @http-samc/hyper
Description: A Javascript SDK for Hyper's API
Author: Samarth Chitgopekar
Latest version: 6.0.9

# hyper.js
A Javascript SDK for Hyper's API

## Installation

### Node.js Projects
```
npm install @http-samc/hyper
```

### Web Projects
*Coming soon!*

## Usage

### Client Initialization
The [Hyper API Client](/classes/default.html) is the default export and needs to be supplied to all calls. It validates and holds your API secret key and an (optional) logger function for development purposes. Import and initialize it as follows:

```js
import { Client } from 'hyper'

const client = Hyper('my-hyper-secret-key')
```

### API Calls
Besides the API Client, each 'category' of endpoints are able to be imported on an as-needed basis via named imports. These are provided as namespaces and their methods correspond to available API calls. You can import them as follows:

```js
import { License, Link, Payment, Product, Waitlist } from 'hyper'

// Use the API by calling the methods of the imported namespaces
License.get(...)
```

If you want to call the namespaces something different, import them directly from their respective directory as follows (you can change the names as you wish):

```js
import * as License from './license'
import * as Link from './link'
import * as Payment from './payment'
import * as Product from './product'
import * as Waitlist from './waitlist'

// Use the API by calling the methods of the imported namespaces
License.get(...)
```

### API Responses
This library is asynchronous, meaning that you'll need to use either `await` or `.then()` to wait for a resolved value. All endpoints return a `Promise` that resolves to a [HyperApiResponse](/interfaces/HyperApiResponse.html). This object contains the response json as-is, straight from the server with the addition of an `ok` boolean property for easy error checking.

Some endpoints resolve to a [HyperApiPaginatedResponse](/interfaces/HyperApiPaginatedResponse.html), a child of [HyperApiResponse](/interfaces/HyperApiResponse.html). This type of response adds an intuitive `.next()` and `.previous` property, which can be used to quickly navigate paginated endpoints. They return `null` once you reach a page that doesn't exist, so use the `has_more` property (supplied on all paginated endpoints) and make sure you aren't calling a page less than 1 before calling either method.

## License
This library is open-sourced under an MIT license and was written by [Samarth Chitgopekar](https://smrth.dev). *It is not officially recognized, endorsed, or maintained by Hyper*.