Full Code of iamolegga/nestjs-session for AI

master cee9ba6dd773 cached
58 files
58.5 KB
16.6k tokens
43 symbols
1 requests
Download .txt
Repository: iamolegga/nestjs-session
Branch: master
Commit: cee9ba6dd773
Files: 58
Total size: 58.5 KB

Directory structure:
gitextract_yuzb6sdt/

├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   ├── feature_request.md
│   │   └── question.md
│   ├── dependabot.yml
│   └── workflows/
│       ├── build-lint-test.yml
│       ├── on-pr-master.yml
│       ├── on-push-master.yml
│       ├── on-release.yml
│       ├── publish-alpha.yml
│       ├── publish-coverage.yml
│       └── publish-with-git-tag-version.yml
├── .gitignore
├── .mergify.yml
├── .prettierrc
├── .vscode/
│   └── settings.json
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── __tests__/
│   ├── forRoot.spec.ts
│   ├── forRootAsync.spec.ts
│   ├── retires.spec.ts
│   ├── routing.spec.ts
│   └── utils/
│       ├── platforms.ts
│       └── request.ts
├── eslint.config.cjs
├── examples/
│   ├── in-memory/
│   │   ├── .eslintrc.js
│   │   ├── .gitignore
│   │   ├── .prettierrc
│   │   ├── README.md
│   │   ├── nest-cli.json
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── app.controller.ts
│   │   │   ├── app.module.ts
│   │   │   └── main.ts
│   │   ├── tsconfig.build.json
│   │   └── tsconfig.json
│   └── redis-store/
│       ├── .eslintrc.js
│       ├── .gitignore
│       ├── .prettierrc
│       ├── README.md
│       ├── nest-cli.json
│       ├── package.json
│       ├── src/
│       │   ├── app.controller.ts
│       │   ├── app.module.ts
│       │   ├── config.module.ts
│       │   ├── config.service.ts
│       │   ├── main.ts
│       │   ├── redis.module.ts
│       │   └── session.module.ts
│       ├── tsconfig.build.json
│       └── tsconfig.json
├── jest.config.js
├── package.json
├── src/
│   ├── index.ts
│   └── retriesMiddleware.ts
├── tsconfig.build.json
└── tsconfig.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: "[BUG] "
labels: bug
assignees: iamolegga

---

<!-- Please don't delete this template or we'll close your issue -->
<!-- Before creating an issue please make sure you are using the latest version. -->

[ ] I've read [the docs](https://github.com/iamolegga/nestjs-session/blob/master/README.md)

[ ] I've read [the docs of express-session](https://github.com/expressjs/session/blob/master/README.md)

[ ] I couldn't find the same [bug](https://github.com/iamolegga/nestjs-session/issues?q=is%3Aissue+label%3Abug)

**What is the current behavior?**

**What is the expected behavior?**

**Please provide minimal example repo. Without it this issue will be closed**

**Please mention other relevant information such as Node.js version and Operating System.**


================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: "[FEATURE REQUEST] "
labels: enhancement
assignees: iamolegga

---

<!-- Please don't delete this template or we'll close your issue -->
<!-- Before creating an issue please make sure you are using the latest version. -->

[ ] I've read [the docs](https://github.com/iamolegga/nestjs-session/blob/master/README.md)

[ ] I've read [the docs of express-session](https://github.com/expressjs/session/blob/master/README.md)

[ ] I couldn't find the same [feature request](https://github.com/iamolegga/nestjs-session/issues?q=is%3Aissue+label%3Aenhancement)

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.


================================================
FILE: .github/ISSUE_TEMPLATE/question.md
================================================
---
name: Question
about: Please ask your question
title: "[QUESTION] "
labels: question
assignees: iamolegga

---

<!-- Please don't delete this template or we'll close your issue -->
<!-- Before creating an issue please make sure you are using the latest version. -->

[ ] I've read [the docs](https://github.com/iamolegga/nestjs-session/blob/master/README.md)

[ ] I've read [the docs of express-session](https://github.com/expressjs/session/blob/master/README.md)

[ ] I couldn't find the same [question](https://github.com/iamolegga/nestjs-session/issues?q=is%3Aissue+label%3Aquestion)

**Question**



**Please mention other relevant information such as Node.js version and Operating System.**




================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: npm
  directory: "/"
  schedule:
    interval: daily
    time: "02:00"
  open-pull-requests-limit: 10
  ignore:
    - dependency-name: "reflect-metadata"
      update-types: ["version-update:semver-major", "version-update:semver-minor"]


================================================
FILE: .github/workflows/build-lint-test.yml
================================================
name: build-lint-test

on:
  workflow_call:

jobs:
  build-lint-test:
    strategy:
      fail-fast: false
      matrix:
        nestjs-version:
          - "8"
          - "9"
          - "10"
          - "11"
        nodejs-version:
          - 20
          - 22
        include:
          - nestjs-version: 8
            typescript-version: 4
          - nestjs-version: 9
            typescript-version: 4
          - nestjs-version: 10
            typescript-version: 5
          - nestjs-version: 11
            typescript-version: 5
    
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.nodejs-version }}
      - run: npm ci
      - run: |
          npm i @nestjs/core@${{ matrix.nestjs-version }} \
                @nestjs/common@${{ matrix.nestjs-version }} \
                @nestjs/platform-express@${{ matrix.nestjs-version }} \
                @types/node@${{ matrix.nodejs-version }} \
                typescript@${{ matrix.typescript-version }} \
                -D
      - run: npm run lint
      - uses: actions/cache@v3
        with:
          path: coverage
          key: ${{ github.sha }}-${{ matrix.nestjs-version }}-${{ matrix.nodejs-version }}
      - run: npm t
      - run: npm run build


================================================
FILE: .github/workflows/on-pr-master.yml
================================================
name: on-pr-master

on:
  pull_request:
    branches:
      - master

jobs:
  build-lint-test:
    uses: ./.github/workflows/build-lint-test.yml
    secrets: inherit


================================================
FILE: .github/workflows/on-push-master.yml
================================================
name: on-push

on:
  push:
    branches:
      - master

jobs:
  build-lint-test:
    uses: ./.github/workflows/build-lint-test.yml
    secrets: inherit

  publish-alpha:
    if: github.actor != 'dependabot[bot]' && github.actor != 'mergify[bot]'
    needs:
      - build-lint-test
    uses: ./.github/workflows/publish-alpha.yml
    secrets: inherit

  coverage:
    needs:
      - build-lint-test
    uses: ./.github/workflows/publish-coverage.yml
    secrets: inherit


================================================
FILE: .github/workflows/on-release.yml
================================================
name: on-release

on:
  release:
    types: [created]

jobs:
  publish-with-git-tag-version:
    uses: ./.github/workflows/publish-with-git-tag-version.yml
    secrets: inherit


================================================
FILE: .github/workflows/publish-alpha.yml
================================================
name: publish-alpha

on:
  workflow_call:

jobs:
  publish-alpha:
    if: github.ref == 'refs/heads/master' && github.actor != 'dependabot[bot]' && github.actor != 'mergify[bot]'
    runs-on: ubuntu-latest
    steps:

      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - uses: actions/setup-node@v3
        with:
          node-version: 22
          registry-url: 'https://registry.npmjs.org'

      - run: npm ci

      - run: npm version --no-git-tag-version $(git describe --abbrev=0 --tags)-alpha.$(git rev-parse --short=6 ${{ github.sha }}) || true

      - run: npm publish --tag alpha || true
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}


================================================
FILE: .github/workflows/publish-coverage.yml
================================================
name: publish-coverage

on:
  workflow_call:

jobs:
  publish-coverage:
    runs-on: ubuntu-latest
    steps:

      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - uses: actions/cache@v3
        with:
          path: coverage
          # restore cache from build-lint-test wf with key=sha-(oneof nestjs version)-(oneof nodejs version)
          key: ${{ github.sha }}-11-22

      - uses: paambaati/codeclimate-action@v2.7.5
        with:
          coverageLocations: ${{github.workspace}}/coverage/lcov.info:lcov
        env:
          CC_TEST_REPORTER_ID: ${{ secrets.CODE_CLIMATE_REPORTER_ID }}


================================================
FILE: .github/workflows/publish-with-git-tag-version.yml
================================================
name: publish-with-git-tag-version

on:
  workflow_call:

jobs:
  publish-with-git-tag-version:
    runs-on: ubuntu-latest
    steps:

      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - uses: actions/setup-node@v3
        with:
          node-version: 22
          registry-url: 'https://registry.npmjs.org'

      - run: npm ci

      - run: npm version --no-git-tag-version $(git describe --abbrev=0 --tags)

      - run: |
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"
          git commit -m "update version" -a

      - uses: ad-m/github-push-action@master
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}

      - run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}


================================================
FILE: .gitignore
================================================
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port


================================================
FILE: .mergify.yml
================================================
queue_rules:
  - name: dependabot-nestjs-session
    queue_conditions:
      - author~=^dependabot(|-preview)\[bot\]$
      - -check-failure~=build-lint-test
      - check-success~=build-lint-test
      - check-success=security/snyk (iamolegga)
    merge_conditions:
      - author~=^dependabot(|-preview)\[bot\]$
      - -check-failure~=build-lint-test
      - check-success~=build-lint-test
      - check-success=security/snyk (iamolegga)
    merge_method: rebase

pull_request_rules:
  - name: refactored queue action rule
    conditions: []
    actions:
      queue:


================================================
FILE: .prettierrc
================================================
{
  "singleQuote": true,
  "trailingComma": "all"
}


================================================
FILE: .vscode/settings.json
================================================
{
  "typescript.tsdk": "node_modules/typescript/lib"
}

================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
 advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
 address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
 professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at iamolegga@gmail.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq


================================================
FILE: CONTRIBUTING.md
================================================
All pull requests that respect next rules are welcome:

- Before opening pull request to this repo run `npm t` to run tests.
- All bugfixes and features should contain tests and coverage must be 100%


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2019 iamolegga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.md
================================================
<h1 align="center">NestJS-Session</h1>

<p align="center">
  <a href="https://www.npmjs.com/package/nestjs-session">
    <img alt="npm" src="https://img.shields.io/npm/v/nestjs-session" />
  </a>
  <a href="https://www.npmjs.com/package/nestjs-session">
    <img alt="npm" src="https://img.shields.io/npm/dm/nestjs-session" />
  </a>
  <a href="https://github.com/iamolegga/nestjs-session/actions">
    <img alt="GitHub branch checks state" src="https://badgen.net/github/checks/iamolegga/nestjs-session" />
  </a>
  <a href="https://codeclimate.com/github/iamolegga/nestjs-session/test_coverage">
    <img src="https://api.codeclimate.com/v1/badges/08bcbca7b2da14b3bbfd/test_coverage" />
  </a>
  <a href="https://snyk.io/test/github/iamolegga/nestjs-session">
    <img alt="Known Vulnerabilities" src="https://snyk.io/test/github/iamolegga/nestjs-session/badge.svg" />
  </a>
  <a href="https://libraries.io/npm/nestjs-session">
    <img alt="Libraries.io" src="https://img.shields.io/librariesio/release/npm/nestjs-session" />
  </a>
  <img alt="Dependabot" src="https://badgen.net/github/dependabot/iamolegga/nestjs-session" />
  <img alt="Supported platforms: Express" src="https://img.shields.io/badge/platforms-Express-green" />
</p>

<p align="center">Idiomatic Session Module for NestJS. Built on top of <a href="https://npm.im/express-session">express-session</a> 😎</p>

This module implements a session with storing data in one of [external stores](https://github.com/expressjs/session#compatible-session-stores) and passing ID of session to client via `Cookie`/`Set-Cookie` headers.

If you want to store data directly in `Cookie`, you can look at [nestjs-cookie-session](https://github.com/iamolegga/nestjs-cookie-session).

## Example

Register module:

```ts
// app.module.ts
import { Module } from '@nestjs/common';
import { NestSessionOptions, SessionModule } from 'nestjs-session';
import { ViewsController } from './views.controller';

@Module({
  imports: [
    // sync params:

    SessionModule.forRoot({
      session: { secret: 'keyboard cat' },
    }),

    // or async:

    SessionModule.forRootAsync({
      imports: [ConfigModule],
      inject: [Config],
      //              TIP: to get autocomplete in return object
      //                  add `NestSessionOptions` here ↓↓↓
      useFactory: async (config: Config): Promise<NestSessionOptions> => {
        return {
          session: { secret: config.secret },
        };
      },
    }),
  ],
  controllers: [ViewsController],
})
export class AppModule {}
```

In controllers use NestJS built-in `Session` decorator:

```ts
// views.controller.ts
import { Controller, Get, Session } from '@nestjs/common';

@Controller('views')
export class ViewsController {
  @Get()
  getViews(@Session() session: { views?: number }) {
    session.views = (session.views || 0) + 1;
    return session.views;
  }
}
```

---

**BE AWARE THAT THIS EXAMPLE IS NOT FOR PRODUCTION! IT USES IN-MEMORY STORE, SO YOUR DATA WILL BE LOST ON RESTART. USE OTHER [STORES](https://github.com/expressjs/session#compatible-session-stores)**

---

See [redis-store](https://github.com/tj/connect-redis) example in `examples` folder.

To run examples:

```sh
git clone https://github.com/iamolegga/nestjs-session.git
cd nestjs-session
npm i
npm run build
cd examples/in-memory # or `cd examples/redis-store`
npm i
npm start
```

For Redis example, you should start Redis on localhost:6379.
If you have Docker installed you can start Redis image by `npm run redis` from `redis-store` directory.

## Install

```sh
npm i nestjs-session express-session @types/express-session
```

## API

### SessionModule

`SessionModule` class has two static methods, that returns `DynamicModule`, that you need to import:

- `SessionModule.forRoot` for sync configuration without dependencies
- `SessionModule.forRootAsync` for sync/async configuration with dependencies

### SessionModule.forRoot

Accept `NestSessionOptions`. Returns NestJS `DynamicModule` for import.

### SessionModule.forRootAsync

Accept `NestSessionAsyncOptions`. Returns NestJS `DynamicModule` for import.

### NestSessionOptions

`NestSessionOptions` is the interface of all options. It has next properties:

- `session` - **required** - [express-session options](https://github.com/expressjs/session#options).
- `forRoutes` - **optional** - same as NestJS buil-in `MiddlewareConfigProxy['forRoutes']` [See examples in official docs](https://docs.nestjs.com/middleware#applying-middleware). Specify routes, that should have access to session. If `forRoutes` and `exclude` will not be set, then sessions will be set to all routes.
- `exclude` - **optional** - same as NestJS buil-in `MiddlewareConfigProxy['exclude']` [See examples in official docs](https://docs.nestjs.com/middleware#applying-middleware). Specify routes, that should not have access to session. If `forRoutes` and `exclude` will not be set, then sessions will be set to all routes.
- `retries` - **optional** - `number` - by default if your session store lost connection to database it will return session as `undefined`, and no errors will be thrown, and then you need to check session in controller. But you can set this property how many times it should retry to get session, and on fail `InternalServerErrorException` will be thrown. If you don't want retries, but just want to `InternalServerErrorException` to be throw, then set to `0`. Set this option, if you dont't want manualy check session inside controllers.
- `retriesStrategy` - **optional** - `(attempt: number) => number` - function that returns number of ms to wait between next attempt. Not calls on first attempt.

### NestSessionAsyncOptions

`NestSessionAsyncOptions` is the interface of options to create session module, that depends on other modules. It has next properties:

- `imports` - **optional** - modules, that session module depends on. See [official docs](https://docs.nestjs.com/modules).
- `inject` - **optional** - providers from `imports`-property modules, that will be passed as arguments to `useFactory` method.
- `useFactory` - **required** - method, that returns `NestSessionOptions`.

## Migration

### v2

`express-session` and `@types/express-session` are moved to peer dependencies, so you can update them independently.

<h2 align="center">Do you use this library?<br/>Don't be shy to give it a star! ★</h2>

<h3 align="center">Also if you are into NestJS you might be interested in one of my <a href="https://github.com/iamolegga#nestjs">other NestJS libs</a>.</h3>


================================================
FILE: __tests__/forRoot.spec.ts
================================================
import { Controller, Get, Module, Session } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

import { SessionModule } from '../src';

import { platforms } from './utils/platforms';
import { doubleRequest } from './utils/request';

describe(SessionModule.forRoot.name, () => {
  for (const PlatformAdapter of platforms) {
    describe(PlatformAdapter.name, () => {
      it('works', async () => {
        @Controller('/')
        class TestController {
          @Get()
          get(@Session() session?: { views?: number }) {
            if (!session) {
              return { views: 0 };
            }

            session.views = (session.views || 0) + 1;
            return { views: session.views };
          }
        }

        @Module({
          imports: [SessionModule.forRoot({ session: { secret: 'test' } })],
          controllers: [TestController],
        })
        class TestModule {}

        const app = await NestFactory.create(
          TestModule,
          new PlatformAdapter(),
          { logger: false },
        );
        const server = app.getHttpServer();

        await app.init();
        const [res1, res2] = await doubleRequest(server);
        await app.close();

        expect(res1.body.views).toBe(1);
        expect(res2.body.views).toBe(2);
      });
    });
  }
});


================================================
FILE: __tests__/forRootAsync.spec.ts
================================================
import { Controller, Get, Module, Session } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

import { NestSessionOptions, SessionModule } from '../src';

import { platforms } from './utils/platforms';
import { doubleRequest } from './utils/request';

describe(SessionModule.forRootAsync.name, () => {
  for (const PlatformAdapter of platforms) {
    describe(PlatformAdapter.name, () => {
      it('works', async () => {
        @Controller('/')
        class TestController {
          @Get()
          get(@Session() session?: { views?: number }) {
            if (!session) {
              return { views: 0 };
            }

            session.views = (session.views || 0) + 1;
            return { views: session.views };
          }
        }

        @Module({
          imports: [
            SessionModule.forRootAsync({
              useFactory: ():
                | NestSessionOptions
                | Promise<NestSessionOptions> => ({
                session: { secret: 'test' },
              }),
            }),
          ],
          controllers: [TestController],
        })
        class TestModule {}

        const app = await NestFactory.create(
          TestModule,
          new PlatformAdapter(),
          { logger: false },
        );
        const server = app.getHttpServer();

        await app.init();
        const [res1, res2] = await doubleRequest(server);
        await app.close();

        expect(res1.body.views).toBe(1);
        expect(res2.body.views).toBe(2);
      });
    });
  }
});


================================================
FILE: __tests__/retires.spec.ts
================================================
import { Controller, Get, Module, Session } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { Handler } from 'express';
import { MemoryStore } from 'express-session';
import request from 'supertest';

import { SessionModule } from '../src';

import { platforms } from './utils/platforms';
import { doubleRequest } from './utils/request';

describe('retries', () => {
  for (const PlatformAdapter of platforms) {
    describe(PlatformAdapter.name, () => {
      it('session is undefined with disconnected store', async () => {
        @Controller('/')
        class TestController {
          @Get()
          get(@Session() session?: { views?: number }) {
            return { sessionType: typeof session };
          }
        }

        const store = new MemoryStore();

        @Module({
          imports: [
            SessionModule.forRoot({ session: { secret: 'test', store } }),
          ],
          controllers: [TestController],
        })
        class TestModule {}

        const app = await NestFactory.create(
          TestModule,
          new PlatformAdapter(),
          { logger: false },
        );
        const server = app.getHttpServer();

        await app.init();

        store.emit('disconnect');

        const result = await request(server).get('/');
        await app.close();

        expect(result.body).toEqual({ sessionType: 'undefined' });
      });

      it('controllers should be blocked with disconnected store and set retries', async () => {
        let isControllerCalled = false;

        @Controller('/')
        class TestController {
          @Get()
          get() {
            isControllerCalled = true;
          }
        }

        const store = new MemoryStore();

        @Module({
          imports: [
            SessionModule.forRoot({
              session: { secret: 'test', store },
              retries: 0,
            }),
          ],
          controllers: [TestController],
        })
        class TestModule {}

        const app = await NestFactory.create(
          TestModule,
          new PlatformAdapter(),
          { logger: false },
        );
        const server = app.getHttpServer();

        await app.init();

        store.emit('disconnect');
        const result = await request(server).get('/');
        await app.close();

        expect(result.status).toBe(500);
        expect(isControllerCalled).toBeFalsy();
      });

      it('retries should work when reconnected', async () => {
        let isControllerCalled = false;

        @Controller('/')
        class TestController {
          @Get()
          get() {
            isControllerCalled = true;
          }
        }

        const store = new MemoryStore();

        @Module({
          imports: [
            SessionModule.forRoot({
              session: { secret: 'test', store },
              retries: 1,
            }),
          ],
          controllers: [TestController],
        })
        class TestModule {}

        const app = await NestFactory.create(
          TestModule,
          new PlatformAdapter(),
          { logger: false },
        );
        app.use(((_req, _res, next) => {
          next();
          process.nextTick(() => {
            store.emit('connect');
          });
        }) as Handler);
        const server = app.getHttpServer();

        await app.init();

        store.emit('disconnect');
        const reqPromise = request(server).get('/');

        const result = await reqPromise;
        await app.close();

        expect(result.status).toBe(200);
        expect(isControllerCalled).toBeTruthy();
      });

      it('controllers should be blocked with error in store and set retries', async () => {
        let callTimes = 0;

        @Controller('/')
        class TestController {
          @Get()
          get() {
            callTimes++;
          }
        }

        const store = new MemoryStore();
        store.get = (_sid, cb) => cb(new Error());

        @Module({
          imports: [
            SessionModule.forRoot({
              session: { secret: 'test', store },
              retries: 0,
            }),
          ],
          controllers: [TestController],
        })
        class TestModule {}

        const app = await NestFactory.create(
          TestModule,
          new PlatformAdapter(),
          { logger: false },
        );
        const server = app.getHttpServer();

        await app.init();

        const [, result] = await doubleRequest(server);
        await app.close();

        expect(result.status).toBe(500);
        expect(callTimes).toBe(1);
      });
    });
  }
});


================================================
FILE: __tests__/routing.spec.ts
================================================
import {
  Controller,
  Get,
  Module,
  RequestMethod,
  Session,
} from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

import { SessionModule } from '../src';

import { platforms } from './utils/platforms';
import { doubleRequest } from './utils/request';

describe('routing', () => {
  for (const PlatformAdapter of platforms) {
    describe(PlatformAdapter.name, () => {
      it('forRoutes', async () => {
        @Controller('/')
        class TestController {
          @Get('with-session')
          withSession(@Session() session?: { views?: number }) {
            if (!session) {
              return { views: 1 };
            }
            session.views = (session.views || 0) + 1;
            return { views: session.views };
          }

          @Get('without-session')
          withoutSession(@Session() session?: { views?: number }) {
            if (!session) {
              return { views: 1 };
            }

            session.views = (session.views || 0) + 1;
            return { views: session.views };
          }
        }

        @Module({
          imports: [
            SessionModule.forRoot({
              session: { secret: 'test' },
              forRoutes: [{ method: RequestMethod.ALL, path: 'with-session' }],
            }),
          ],
          controllers: [TestController],
        })
        class TestModule {}

        const app = await NestFactory.create(
          TestModule,
          new PlatformAdapter(),
          { logger: false },
        );
        const server = app.getHttpServer();

        await app.init();
        const [sessRes1, sessRes2] = await doubleRequest(
          server,
          '/with-session',
        );
        const [noSessRes1, noSessRes2] = await doubleRequest(
          server,
          '/without-session',
        );
        await app.close();

        expect(sessRes1.body.views).toBe(1);
        expect(sessRes2.body.views).toBe(2);

        expect(noSessRes1.body.views).toBe(1);
        expect(noSessRes2.body.views).toBe(1);
      });

      it('exclude', async () => {
        @Controller('/')
        class TestController {
          @Get('with-session')
          withSession(@Session() session?: { views?: number }) {
            if (!session) {
              return { views: 1 };
            }
            session.views = (session.views || 0) + 1;
            return { views: session.views };
          }

          @Get('without-session')
          withoutSession(@Session() session?: { views?: number }) {
            if (!session) {
              return { views: 1 };
            }

            session.views = (session.views || 0) + 1;
            return { views: session.views };
          }
        }

        @Module({
          imports: [
            SessionModule.forRoot({
              session: { secret: 'test' },
              exclude: [{ method: RequestMethod.ALL, path: 'without-session' }],
              forRoutes: [TestController],
            }),
          ],
          controllers: [TestController],
        })
        class TestModule {}

        const app = await NestFactory.create(
          TestModule,
          new PlatformAdapter(),
          { logger: false },
        );
        const server = app.getHttpServer();

        await app.init();
        const [sessRes1, sessRes2] = await doubleRequest(
          server,
          '/with-session',
        );
        const [noSessRes1, noSessRes2] = await doubleRequest(
          server,
          '/without-session',
        );
        await app.close();

        expect(sessRes1.body.views).toBe(1);
        expect(sessRes2.body.views).toBe(2);

        expect(noSessRes1.body.views).toBe(1);
        expect(noSessRes2.body.views).toBe(1);
      });
    });
  }
});


================================================
FILE: __tests__/utils/platforms.ts
================================================
import { Type } from '@nestjs/common';
import { AbstractHttpAdapter } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Adapter = Type<AbstractHttpAdapter<any, any, any>>;

export const platforms: Adapter[] = [ExpressAdapter];


================================================
FILE: __tests__/utils/request.ts
================================================
import request from 'supertest';

export async function doubleRequest(
  server: Parameters<typeof request>[0],
  path = '/',
) {
  const result1 = await request(server).get(path);

  const cookie = result1.header['set-cookie'];

  const result2 = await request(server)
    .get(path)
    .set('Cookie', cookie ? [cookie] : []);

  return [result1, result2] as [request.Response, request.Response];
}


================================================
FILE: eslint.config.cjs
================================================
const { fixupConfigRules, fixupPluginRules } = require('@eslint/compat');
const { FlatCompat } = require('@eslint/eslintrc');
const js = require('@eslint/js');
const typescriptEslintEslintPlugin = require('@typescript-eslint/eslint-plugin');
const tsParser = require('@typescript-eslint/parser');
const globals = require('globals');

const compat = new FlatCompat({
  baseDirectory: __dirname,
  recommendedConfig: js.configs.recommended,
  allConfig: js.configs.all,
});

module.exports = [
  {
    ignores: ['eslint.config.cjs'],
  },
  ...fixupConfigRules(
    compat.extends(
      'plugin:@typescript-eslint/recommended',
      'plugin:import/recommended',
      'plugin:import/typescript',
      'plugin:prettier/recommended',
    ),
  ),
  {
    plugins: {
      '@typescript-eslint': fixupPluginRules(typescriptEslintEslintPlugin),
    },

    languageOptions: {
      globals: {
        ...globals.node,
        ...globals.jest,
      },

      parser: tsParser,
      ecmaVersion: 5,
      sourceType: 'module',

      parserOptions: {
        project: 'tsconfig.json',
      },
    },

    rules: {
      '@typescript-eslint/no-explicit-any': [
        'error',
        {
          fixToUnknown: true,
          ignoreRestArgs: false,
        },
      ],

      '@typescript-eslint/no-floating-promises': [
        'error',
        {
          ignoreIIFE: true,
        },
      ],

      '@typescript-eslint/no-unused-vars': [
        'error',
        {
          varsIgnorePattern: '^_',
          argsIgnorePattern: '^_',
          ignoreRestSiblings: true,
        },
      ],

      '@typescript-eslint/explicit-member-accessibility': [
        'error',
        {
          accessibility: 'no-public',
        },
      ],

      '@typescript-eslint/member-ordering': [
        'error',
        {
          default: [
            'public-static-field',
            'public-static-get',
            'public-static-set',
            'public-static-method',
            'protected-static-field',
            'protected-static-get',
            'protected-static-set',
            'protected-static-method',
            'private-static-field',
            'private-static-get',
            'private-static-set',
            'private-static-method',
            'signature',
            'public-abstract-field',
            'protected-abstract-field',
            'public-decorated-field',
            'public-instance-field',
            'protected-decorated-field',
            'protected-instance-field',
            'private-decorated-field',
            'private-instance-field',
            'public-constructor',
            'protected-constructor',
            'private-constructor',
            'public-abstract-get',
            'public-abstract-set',
            'public-abstract-method',
            'public-decorated-get',
            'public-instance-get',
            'public-decorated-set',
            'public-instance-set',
            'public-decorated-method',
            'public-instance-method',
            'protected-abstract-get',
            'protected-abstract-set',
            'protected-abstract-method',
            'protected-decorated-get',
            'protected-instance-get',
            'protected-decorated-set',
            'protected-instance-set',
            'protected-decorated-method',
            'protected-instance-method',
            'private-decorated-get',
            'private-instance-get',
            'private-decorated-set',
            'private-instance-set',
            'private-decorated-method',
            'private-instance-method',
          ],
        },
      ],

      'import/order': [
        'error',
        {
          alphabetize: {
            order: 'asc',
            caseInsensitive: true,
          },

          'newlines-between': 'always',
        },
      ],
    },
  },
];


================================================
FILE: examples/in-memory/.eslintrc.js
================================================
module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: 'tsconfig.json',
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint/eslint-plugin'],
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  root: true,
  env: {
    node: true,
    jest: true,
  },
  ignorePatterns: ['.eslintrc.js'],
  rules: {
    '@typescript-eslint/interface-name-prefix': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
  },
};


================================================
FILE: examples/in-memory/.gitignore
================================================
# compiled output
/dist
/node_modules

# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# OS
.DS_Store

# Tests
/coverage
/.nyc_output

# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace

# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

================================================
FILE: examples/in-memory/.prettierrc
================================================
{
  "singleQuote": true,
  "trailingComma": "all"
}

================================================
FILE: examples/in-memory/README.md
================================================
<p align="center">
  <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a>
</p>

[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest

  <p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
    <p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
  <a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
    <a href="https://opencollective.com/nest#sponsor"  target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
  <a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
  <!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
  [![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->

## Description

[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.

## Installation

```bash
$ npm install
```

## Running the app

```bash
# development
$ npm run start

# watch mode
$ npm run start:dev

# production mode
$ npm run start:prod
```

## Test

```bash
# unit tests
$ npm run test

# e2e tests
$ npm run test:e2e

# test coverage
$ npm run test:cov
```

## Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).

## Stay in touch

- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)

## License

Nest is [MIT licensed](LICENSE).


================================================
FILE: examples/in-memory/nest-cli.json
================================================
{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src"
}


================================================
FILE: examples/in-memory/package.json
================================================
{
  "name": "in-memory",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "private": true,
  "license": "UNLICENSED",
  "scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },
  "dependencies": {
    "@nestjs/common": "^11.0.16",
    "@nestjs/core": "^11.1.18",
    "@nestjs/platform-express": "^11.1.19",
    "@types/express-session": "^1.17.4",
    "express-session": "^1.18.2",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^7.2.0"
  },
  "devDependencies": {
    "@nestjs/cli": "^11.0.16",
    "@nestjs/schematics": "^8.0.0",
    "@nestjs/testing": "^11.0.16",
    "@types/express": "^4.17.13",
    "@types/jest": "^27.0.1",
    "@types/node": "^16.0.0",
    "@types/supertest": "^2.0.11",
    "@typescript-eslint/eslint-plugin": "^4.28.2",
    "@typescript-eslint/parser": "^4.28.2",
    "eslint": "^7.30.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^3.4.0",
    "jest": "^30.2.0",
    "prettier": "^2.3.2",
    "supertest": "^7.0.0",
    "ts-jest": "^27.0.3",
    "ts-loader": "^9.2.3",
    "ts-node": "^10.0.0",
    "tsconfig-paths": "^3.14.1",
    "typescript": "^4.3.5"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}


================================================
FILE: examples/in-memory/src/app.controller.ts
================================================
import { Controller, Get, Session } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  getHello(@Session() session: { views?: number }) {
    session.views = (session.views || 0) + 1;
    return session.views;
  }
}


================================================
FILE: examples/in-memory/src/app.module.ts
================================================
import { Module } from '@nestjs/common';
import { SessionModule } from '../../../dist';
import { AppController } from './app.controller';

@Module({
  imports: [
    SessionModule.forRoot({
      session: { secret: 'qwerty' },
    }),
  ],
  controllers: [AppController],
})
export class AppModule {}


================================================
FILE: examples/in-memory/src/main.ts
================================================
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();


================================================
FILE: examples/in-memory/tsconfig.build.json
================================================
{
  "extends": "./tsconfig.json",
  "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}


================================================
FILE: examples/in-memory/tsconfig.json
================================================
{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  }
}


================================================
FILE: examples/redis-store/.eslintrc.js
================================================
module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: 'tsconfig.json',
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint/eslint-plugin'],
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  root: true,
  env: {
    node: true,
    jest: true,
  },
  ignorePatterns: ['.eslintrc.js'],
  rules: {
    '@typescript-eslint/interface-name-prefix': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
  },
};


================================================
FILE: examples/redis-store/.gitignore
================================================
# compiled output
/dist
/node_modules

# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# OS
.DS_Store

# Tests
/coverage
/.nyc_output

# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace

# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

================================================
FILE: examples/redis-store/.prettierrc
================================================
{
  "singleQuote": true,
  "trailingComma": "all"
}

================================================
FILE: examples/redis-store/README.md
================================================
<p align="center">
  <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a>
</p>

[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest

  <p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
    <p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
  <a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
    <a href="https://opencollective.com/nest#sponsor"  target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
  <a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
  <!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
  [![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->

## Description

[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.

## Installation

```bash
$ npm install
```

## Running the app

```bash
# development
$ npm run start

# watch mode
$ npm run start:dev

# production mode
$ npm run start:prod
```

## Test

```bash
# unit tests
$ npm run test

# e2e tests
$ npm run test:e2e

# test coverage
$ npm run test:cov
```

## Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).

## Stay in touch

- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)

## License

Nest is [MIT licensed](LICENSE).


================================================
FILE: examples/redis-store/nest-cli.json
================================================
{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src"
}


================================================
FILE: examples/redis-store/package.json
================================================
{
  "name": "redis-store",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "private": true,
  "license": "UNLICENSED",
  "scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json",
    "redis": "docker run -p 6379:6379 redis"
  },
  "dependencies": {
    "@nestjs/common": "^11.0.16",
    "@nestjs/core": "^11.1.18",
    "@nestjs/platform-express": "^11.1.16",
    "@types/connect-redis": "^0.0.17",
    "@types/express-session": "^1.17.4",
    "connect-redis": "^6.0.0",
    "express-session": "^1.18.2",
    "nestjs-redis": "^1.3.3",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^7.2.0"
  },
  "devDependencies": {
    "@nestjs/cli": "^11.0.16",
    "@nestjs/schematics": "^8.0.0",
    "@nestjs/testing": "^11.1.13",
    "@types/express": "^4.17.13",
    "@types/jest": "^27.0.1",
    "@types/node": "^16.0.0",
    "@types/supertest": "^2.0.11",
    "@typescript-eslint/eslint-plugin": "^4.28.2",
    "@typescript-eslint/parser": "^4.28.2",
    "eslint": "^7.30.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^3.4.0",
    "jest": "^30.2.0",
    "prettier": "^2.3.2",
    "supertest": "^7.0.0",
    "ts-jest": "^27.0.3",
    "ts-loader": "^9.2.3",
    "ts-node": "^10.0.0",
    "tsconfig-paths": "^3.14.1",
    "typescript": "^4.3.5"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}


================================================
FILE: examples/redis-store/src/app.controller.ts
================================================
import { Controller, Get, Session } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  getHello(@Session() session: { views?: number }) {
    session.views = (session.views || 0) + 1;
    return session.views;
  }
}


================================================
FILE: examples/redis-store/src/app.module.ts
================================================
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { Session } from './session.module';

@Module({
  imports: [Session],
  controllers: [AppController],
})
export class AppModule {}


================================================
FILE: examples/redis-store/src/config.module.ts
================================================
import { Module } from '@nestjs/common';
import { ConfigService } from './config.service';

@Module({
  providers: [ConfigService],
  exports: [ConfigService],
})
export class ConfigModule {}


================================================
FILE: examples/redis-store/src/config.service.ts
================================================
import { Injectable } from '@nestjs/common';

@Injectable()
export class ConfigService {
  public readonly REDIS_PORT = Number(process.env.REDIS_PORT || 6379);
  public readonly REDIS_HOST = process.env.REDIS_HOST;
  public readonly SESSION_SECRET = process.env.SESSION_SECRET || 'supersecret';
}


================================================
FILE: examples/redis-store/src/main.ts
================================================
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();


================================================
FILE: examples/redis-store/src/redis.module.ts
================================================
import { DynamicModule } from '@nestjs/common';
import { RedisModule, RedisModuleOptions } from 'nestjs-redis';
import { ConfigModule } from './config.module';
import { ConfigService } from './config.service';

export const Redis: DynamicModule = RedisModule.forRootAsync({
  imports: [ConfigModule],
  inject: [ConfigService],
  useFactory: (config: ConfigService): RedisModuleOptions => {
    return {
      host: config.REDIS_HOST,
      port: config.REDIS_PORT,
    };
  },
});


================================================
FILE: examples/redis-store/src/session.module.ts
================================================
import * as ConnectRedis from 'connect-redis';
import * as session from 'express-session';
import { RedisService } from 'nestjs-redis';
import { NestSessionOptions, SessionModule } from '../../../dist';
import { ConfigModule } from './config.module';
import { ConfigService } from './config.service';
import { Redis } from './redis.module';

const RedisStore = ConnectRedis(session);

export const Session = SessionModule.forRootAsync({
  imports: [Redis, ConfigModule],
  inject: [RedisService, ConfigService],
  useFactory: (
    redisService: RedisService,
    config: ConfigService,
  ): NestSessionOptions => {
    const redisClient = redisService.getClient();
    const store = new RedisStore({ client: redisClient as any });
    return {
      session: {
        store,
        secret: config.SESSION_SECRET,
      },
    };
  },
});


================================================
FILE: examples/redis-store/tsconfig.build.json
================================================
{
  "extends": "./tsconfig.json",
  "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}


================================================
FILE: examples/redis-store/tsconfig.json
================================================
{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  }
}


================================================
FILE: jest.config.js
================================================
module.exports = {
  moduleFileExtensions: ['js', 'ts'],
  testRegex: '.spec.ts$',
  transform: {
    '^.+\\.(t|j)s$': 'ts-jest',
  },
  collectCoverage: true,
  coverageDirectory: './coverage',
  collectCoverageFrom: ['src/**/*.ts'],
  testEnvironment: 'node',
  setupFiles: [],
};


================================================
FILE: package.json
================================================
{
  "name": "nestjs-session",
  "version": "4.0.0",
  "description": "Idiomatic NestJS module for session",
  "main": "index.js",
  "typings": "index.d.ts",
  "scripts": {
    "test": "jest --verbose -i --detectOpenHandles",
    "lint": "tsc --noemit && eslint \"{src,__tests__}/**/*.ts\" --fix",
    "prebuild": "rimraf dist",
    "build": "tsc -p tsconfig.build.json",
    "prepublishOnly": "npm run build && cp -r ./dist/* .",
    "postpublish": "git clean -fd"
  },
  "files": [
    "*.{js,d.ts}",
    "!jest.config.js",
    "!.eslintrc.js"
  ],
  "engineStrict": true,
  "engines": {
    "node": ">=18.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/iamolegga/nestjs-session.git"
  },
  "keywords": [
    "nestjs",
    "nest.js",
    "nest",
    "session",
    "express",
    "express-session"
  ],
  "author": "iamolegga <iamolegga@gmail.com> (http://github.com/iamolegga)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/iamolegga/nestjs-session/issues"
  },
  "homepage": "https://github.com/iamolegga/nestjs-session#readme",
  "dependencies": {
    "create-nestjs-middleware-module": "^0.4.0"
  },
  "devDependencies": {
    "@eslint/compat": "^2.0.0",
    "@eslint/eslintrc": "^3.2.0",
    "@eslint/js": "^9.18.0",
    "@nestjs/common": "^11.0.4",
    "@nestjs/core": "^11.0.4",
    "@nestjs/platform-express": "^11.0.4",
    "@types/express-session": "^1.18.1",
    "@types/jest": "^29.5.14",
    "@types/node": "^25.0.0",
    "@types/supertest": "^7.2.0",
    "@typescript-eslint/eslint-plugin": "^8.21.0",
    "@typescript-eslint/parser": "^8.21.0",
    "eslint": "^9.18.0",
    "eslint-config-prettier": "^10.0.1",
    "eslint-plugin-import": "^2.31.0",
    "eslint-plugin-prettier": "^5.2.3",
    "express-session": "^1.18.1",
    "jest": "30.0.0",
    "prettier": "^3.4.2",
    "reflect-metadata": "^0.1.14",
    "rimraf": "^6.0.1",
    "rxjs": "^7.8.1",
    "supertest": "^7.0.0",
    "ts-jest": "^29.2.5",
    "ts-loader": "^9.5.2",
    "ts-node": "^10.9.2",
    "typescript": "^6.0.2"
  },
  "peerDependencies": {
    "@types/express-session": "^1.17.4",
    "express-session": "^1.17.2"
  }
}


================================================
FILE: src/index.ts
================================================
import {
  AsyncOptions,
  createModule,
  SyncOptions,
} from 'create-nestjs-middleware-module';
import expressSession from 'express-session';

import { createRetriesMiddleware } from './retriesMiddleware';

interface Options {
  /**
   * express-session options. @see https://github.com/expressjs/session#options
   */
  session: expressSession.SessionOptions;
  /**
   * by default if your session store lost connection to database it will return
   * session as `undefined`, and no errors will be thrown, and then you need to
   * check session in controller. But you can set this property how many times
   * it should retry to get session, and on fail `InternalServerErrorException`
   * will be thrown. If you don't want retries, but just want to
   * `InternalServerErrorException` to be throw, then set to `0`. Set this
   * option, if you dont't want manualy check session inside controllers.
   */
  retries?: number;
  /**
   * function that returns number of ms to wait between next attempt. Not calls
   * on first attempt.
   */
  retriesStrategy?: Parameters<typeof createRetriesMiddleware>[2];
}

export type NestSessionOptions = SyncOptions<Options>;

export type NestSessionAsyncOptions = AsyncOptions<Options>;

export const SessionModule = createModule<Options>((options) => {
  const { retries, session, retriesStrategy } = options;
  let middleware = expressSession(session);

  if (retries !== undefined) {
    middleware = createRetriesMiddleware(middleware, retries, retriesStrategy);
  }

  return middleware;
});


================================================
FILE: src/retriesMiddleware.ts
================================================
import { InternalServerErrorException } from '@nestjs/common';
import * as express from 'express';

type WaitingStrategy = (attempt: number) => number;

export function createRetriesMiddleware(
  sessionMiddleware: express.RequestHandler,
  retries: number,
  retiesStrategy: WaitingStrategy = () => 0,
): express.RequestHandler {
  return async (req, res, next) => {
    let attempt = 0;

    async function lookupSession(error?: unknown) {
      if (error) {
        return next(error);
      }

      if (req.session !== undefined) {
        return next();
      }

      if (attempt > retries) {
        return next(new InternalServerErrorException('Cannot create session'));
      }

      if (attempt !== 0) {
        await new Promise((r) => setTimeout(r, retiesStrategy(attempt)));
      }

      attempt++;

      sessionMiddleware(req, res, lookupSession);
    }

    await lookupSession();
  };
}


================================================
FILE: tsconfig.build.json
================================================
{
  "extends": "./tsconfig.json",
  "exclude": ["node_modules", "dist", "__tests__", "examples"]
}


================================================
FILE: tsconfig.json
================================================
{
  "compilerOptions": {
    "lib": ["ES2022"],
    "module": "node16",
    "target": "ES2022",
    "removeComments": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "sourceMap": true,
    "outDir": "./dist",
    "incremental": true,
    "skipLibCheck": true,
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "typeRoots": ["src/typings", "node_modules/@types"],
    "declaration": true
  },
  "exclude": ["examples"]
}
Download .txt
gitextract_yuzb6sdt/

├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   ├── feature_request.md
│   │   └── question.md
│   ├── dependabot.yml
│   └── workflows/
│       ├── build-lint-test.yml
│       ├── on-pr-master.yml
│       ├── on-push-master.yml
│       ├── on-release.yml
│       ├── publish-alpha.yml
│       ├── publish-coverage.yml
│       └── publish-with-git-tag-version.yml
├── .gitignore
├── .mergify.yml
├── .prettierrc
├── .vscode/
│   └── settings.json
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── __tests__/
│   ├── forRoot.spec.ts
│   ├── forRootAsync.spec.ts
│   ├── retires.spec.ts
│   ├── routing.spec.ts
│   └── utils/
│       ├── platforms.ts
│       └── request.ts
├── eslint.config.cjs
├── examples/
│   ├── in-memory/
│   │   ├── .eslintrc.js
│   │   ├── .gitignore
│   │   ├── .prettierrc
│   │   ├── README.md
│   │   ├── nest-cli.json
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── app.controller.ts
│   │   │   ├── app.module.ts
│   │   │   └── main.ts
│   │   ├── tsconfig.build.json
│   │   └── tsconfig.json
│   └── redis-store/
│       ├── .eslintrc.js
│       ├── .gitignore
│       ├── .prettierrc
│       ├── README.md
│       ├── nest-cli.json
│       ├── package.json
│       ├── src/
│       │   ├── app.controller.ts
│       │   ├── app.module.ts
│       │   ├── config.module.ts
│       │   ├── config.service.ts
│       │   ├── main.ts
│       │   ├── redis.module.ts
│       │   └── session.module.ts
│       ├── tsconfig.build.json
│       └── tsconfig.json
├── jest.config.js
├── package.json
├── src/
│   ├── index.ts
│   └── retriesMiddleware.ts
├── tsconfig.build.json
└── tsconfig.json
Download .txt
SYMBOL INDEX (43 symbols across 16 files)

FILE: __tests__/forRoot.spec.ts
  class TestController (line 13) | @Controller('/')
    method get (line 16) | get(@Session() session?: { views?: number }) {
  class TestModule (line 26) | @Module({

FILE: __tests__/forRootAsync.spec.ts
  class TestController (line 13) | @Controller('/')
    method get (line 16) | get(@Session() session?: { views?: number }) {
  class TestModule (line 26) | @Module({

FILE: __tests__/retires.spec.ts
  class TestController (line 16) | @Controller('/')
    method get (line 19) | get(@Session() session?: { views?: number }) {
    method get (line 57) | get() {
    method get (line 98) | get() {
    method get (line 147) | get() {
  class TestModule (line 26) | @Module({
  class TestController (line 54) | @Controller('/')
    method get (line 19) | get(@Session() session?: { views?: number }) {
    method get (line 57) | get() {
    method get (line 98) | get() {
    method get (line 147) | get() {
  class TestModule (line 64) | @Module({
  class TestController (line 95) | @Controller('/')
    method get (line 19) | get(@Session() session?: { views?: number }) {
    method get (line 57) | get() {
    method get (line 98) | get() {
    method get (line 147) | get() {
  class TestModule (line 105) | @Module({
  class TestController (line 144) | @Controller('/')
    method get (line 19) | get(@Session() session?: { views?: number }) {
    method get (line 57) | get() {
    method get (line 98) | get() {
    method get (line 147) | get() {
  class TestModule (line 155) | @Module({

FILE: __tests__/routing.spec.ts
  class TestController (line 19) | @Controller('/')
    method withSession (line 22) | withSession(@Session() session?: { views?: number }) {
    method withoutSession (line 31) | withoutSession(@Session() session?: { views?: number }) {
    method withSession (line 81) | withSession(@Session() session?: { views?: number }) {
    method withoutSession (line 90) | withoutSession(@Session() session?: { views?: number }) {
  class TestModule (line 41) | @Module({
  class TestController (line 78) | @Controller('/')
    method withSession (line 22) | withSession(@Session() session?: { views?: number }) {
    method withoutSession (line 31) | withoutSession(@Session() session?: { views?: number }) {
    method withSession (line 81) | withSession(@Session() session?: { views?: number }) {
    method withoutSession (line 90) | withoutSession(@Session() session?: { views?: number }) {
  class TestModule (line 100) | @Module({

FILE: __tests__/utils/platforms.ts
  type Adapter (line 6) | type Adapter = Type<AbstractHttpAdapter<any, any, any>>;

FILE: __tests__/utils/request.ts
  function doubleRequest (line 3) | async function doubleRequest(

FILE: examples/in-memory/src/app.controller.ts
  class AppController (line 4) | class AppController {
    method getHello (line 6) | getHello(@Session() session: { views?: number }) {

FILE: examples/in-memory/src/app.module.ts
  class AppModule (line 13) | class AppModule {}

FILE: examples/in-memory/src/main.ts
  function bootstrap (line 4) | async function bootstrap() {

FILE: examples/redis-store/src/app.controller.ts
  class AppController (line 4) | class AppController {
    method getHello (line 6) | getHello(@Session() session: { views?: number }) {

FILE: examples/redis-store/src/app.module.ts
  class AppModule (line 9) | class AppModule {}

FILE: examples/redis-store/src/config.module.ts
  class ConfigModule (line 8) | class ConfigModule {}

FILE: examples/redis-store/src/config.service.ts
  class ConfigService (line 4) | class ConfigService {

FILE: examples/redis-store/src/main.ts
  function bootstrap (line 4) | async function bootstrap() {

FILE: src/index.ts
  type Options (line 10) | interface Options {
  type NestSessionOptions (line 32) | type NestSessionOptions = SyncOptions<Options>;
  type NestSessionAsyncOptions (line 34) | type NestSessionAsyncOptions = AsyncOptions<Options>;

FILE: src/retriesMiddleware.ts
  type WaitingStrategy (line 4) | type WaitingStrategy = (attempt: number) => number;
  function createRetriesMiddleware (line 6) | function createRetriesMiddleware(
Condensed preview — 58 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (67K chars).
[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "chars": 826,
    "preview": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: \"[BUG] \"\nlabels: bug\nassignees: iamolegga\n\n---\n\n<!"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "chars": 1115,
    "preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: \"[FEATURE REQUEST] \"\nlabels: enhancement\nassign"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/question.md",
    "chars": 702,
    "preview": "---\nname: Question\nabout: Please ask your question\ntitle: \"[QUESTION] \"\nlabels: question\nassignees: iamolegga\n\n---\n\n<!--"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 278,
    "preview": "version: 2\nupdates:\n- package-ecosystem: npm\n  directory: \"/\"\n  schedule:\n    interval: daily\n    time: \"02:00\"\n  open-p"
  },
  {
    "path": ".github/workflows/build-lint-test.yml",
    "chars": 1363,
    "preview": "name: build-lint-test\n\non:\n  workflow_call:\n\njobs:\n  build-lint-test:\n    strategy:\n      fail-fast: false\n      matrix:"
  },
  {
    "path": ".github/workflows/on-pr-master.yml",
    "chars": 166,
    "preview": "name: on-pr-master\n\non:\n  pull_request:\n    branches:\n      - master\n\njobs:\n  build-lint-test:\n    uses: ./.github/workf"
  },
  {
    "path": ".github/workflows/on-push-master.yml",
    "chars": 471,
    "preview": "name: on-push\n\non:\n  push:\n    branches:\n      - master\n\njobs:\n  build-lint-test:\n    uses: ./.github/workflows/build-li"
  },
  {
    "path": ".github/workflows/on-release.yml",
    "chars": 177,
    "preview": "name: on-release\n\non:\n  release:\n    types: [created]\n\njobs:\n  publish-with-git-tag-version:\n    uses: ./.github/workflo"
  },
  {
    "path": ".github/workflows/publish-alpha.yml",
    "chars": 694,
    "preview": "name: publish-alpha\n\non:\n  workflow_call:\n\njobs:\n  publish-alpha:\n    if: github.ref == 'refs/heads/master' && github.ac"
  },
  {
    "path": ".github/workflows/publish-coverage.yml",
    "chars": 627,
    "preview": "name: publish-coverage\n\non:\n  workflow_call:\n\njobs:\n  publish-coverage:\n    runs-on: ubuntu-latest\n    steps:\n\n      - u"
  },
  {
    "path": ".github/workflows/publish-with-git-tag-version.yml",
    "chars": 852,
    "preview": "name: publish-with-git-tag-version\n\non:\n  workflow_call:\n\njobs:\n  publish-with-git-tag-version:\n    runs-on: ubuntu-late"
  },
  {
    "path": ".gitignore",
    "chars": 1610,
    "preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# Diagnostic reports (https://nodejs."
  },
  {
    "path": ".mergify.yml",
    "chars": 571,
    "preview": "queue_rules:\n  - name: dependabot-nestjs-session\n    queue_conditions:\n      - author~=^dependabot(|-preview)\\[bot\\]$\n  "
  },
  {
    "path": ".prettierrc",
    "chars": 52,
    "preview": "{\n  \"singleQuote\": true,\n  \"trailingComma\": \"all\"\n}\n"
  },
  {
    "path": ".vscode/settings.json",
    "chars": 54,
    "preview": "{\n  \"typescript.tsdk\": \"node_modules/typescript/lib\"\n}"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "chars": 3351,
    "preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, w"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 200,
    "preview": "All pull requests that respect next rules are welcome:\n\n- Before opening pull request to this repo run `npm t` to run te"
  },
  {
    "path": "LICENSE",
    "chars": 1066,
    "preview": "MIT License\n\nCopyright (c) 2019 iamolegga\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n"
  },
  {
    "path": "README.md",
    "chars": 6543,
    "preview": "<h1 align=\"center\">NestJS-Session</h1>\n\n<p align=\"center\">\n  <a href=\"https://www.npmjs.com/package/nestjs-session\">\n   "
  },
  {
    "path": "__tests__/forRoot.spec.ts",
    "chars": 1327,
    "preview": "import { Controller, Get, Module, Session } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\n\nimport {"
  },
  {
    "path": "__tests__/forRootAsync.spec.ts",
    "chars": 1548,
    "preview": "import { Controller, Get, Module, Session } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\n\nimport {"
  },
  {
    "path": "__tests__/retires.spec.ts",
    "chars": 4649,
    "preview": "import { Controller, Get, Module, Session } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { "
  },
  {
    "path": "__tests__/routing.spec.ts",
    "chars": 3765,
    "preview": "import {\n  Controller,\n  Get,\n  Module,\n  RequestMethod,\n  Session,\n} from '@nestjs/common';\nimport { NestFactory } from"
  },
  {
    "path": "__tests__/utils/platforms.ts",
    "chars": 333,
    "preview": "import { Type } from '@nestjs/common';\nimport { AbstractHttpAdapter } from '@nestjs/core';\nimport { ExpressAdapter } fro"
  },
  {
    "path": "__tests__/utils/request.ts",
    "chars": 401,
    "preview": "import request from 'supertest';\n\nexport async function doubleRequest(\n  server: Parameters<typeof request>[0],\n  path ="
  },
  {
    "path": "eslint.config.cjs",
    "chars": 3867,
    "preview": "const { fixupConfigRules, fixupPluginRules } = require('@eslint/compat');\nconst { FlatCompat } = require('@eslint/eslint"
  },
  {
    "path": "examples/in-memory/.eslintrc.js",
    "chars": 631,
    "preview": "module.exports = {\n  parser: '@typescript-eslint/parser',\n  parserOptions: {\n    project: 'tsconfig.json',\n    sourceTyp"
  },
  {
    "path": "examples/in-memory/.gitignore",
    "chars": 391,
    "preview": "# compiled output\n/dist\n/node_modules\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\npnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n"
  },
  {
    "path": "examples/in-memory/.prettierrc",
    "chars": 51,
    "preview": "{\n  \"singleQuote\": true,\n  \"trailingComma\": \"all\"\n}"
  },
  {
    "path": "examples/in-memory/README.md",
    "chars": 3338,
    "preview": "<p align=\"center\">\n  <a href=\"http://nestjs.com/\" target=\"blank\"><img src=\"https://nestjs.com/img/logo_text.svg\" width=\""
  },
  {
    "path": "examples/in-memory/nest-cli.json",
    "chars": 64,
    "preview": "{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\"\n}\n"
  },
  {
    "path": "examples/in-memory/package.json",
    "chars": 2050,
    "preview": "{\n  \"name\": \"in-memory\",\n  \"version\": \"0.0.1\",\n  \"description\": \"\",\n  \"author\": \"\",\n  \"private\": true,\n  \"license\": \"UNL"
  },
  {
    "path": "examples/in-memory/src/app.controller.ts",
    "chars": 243,
    "preview": "import { Controller, Get, Session } from '@nestjs/common';\n\n@Controller()\nexport class AppController {\n  @Get()\n  getHel"
  },
  {
    "path": "examples/in-memory/src/app.module.ts",
    "chars": 301,
    "preview": "import { Module } from '@nestjs/common';\nimport { SessionModule } from '../../../dist';\nimport { AppController } from '."
  },
  {
    "path": "examples/in-memory/src/main.ts",
    "chars": 208,
    "preview": "import { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  co"
  },
  {
    "path": "examples/in-memory/tsconfig.build.json",
    "chars": 97,
    "preview": "{\n  \"extends\": \"./tsconfig.json\",\n  \"exclude\": [\"node_modules\", \"test\", \"dist\", \"**/*spec.ts\"]\n}\n"
  },
  {
    "path": "examples/in-memory/tsconfig.json",
    "chars": 546,
    "preview": "{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecorat"
  },
  {
    "path": "examples/redis-store/.eslintrc.js",
    "chars": 631,
    "preview": "module.exports = {\n  parser: '@typescript-eslint/parser',\n  parserOptions: {\n    project: 'tsconfig.json',\n    sourceTyp"
  },
  {
    "path": "examples/redis-store/.gitignore",
    "chars": 391,
    "preview": "# compiled output\n/dist\n/node_modules\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\npnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n"
  },
  {
    "path": "examples/redis-store/.prettierrc",
    "chars": 51,
    "preview": "{\n  \"singleQuote\": true,\n  \"trailingComma\": \"all\"\n}"
  },
  {
    "path": "examples/redis-store/README.md",
    "chars": 3338,
    "preview": "<p align=\"center\">\n  <a href=\"http://nestjs.com/\" target=\"blank\"><img src=\"https://nestjs.com/img/logo_text.svg\" width=\""
  },
  {
    "path": "examples/redis-store/nest-cli.json",
    "chars": 64,
    "preview": "{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\"\n}\n"
  },
  {
    "path": "examples/redis-store/package.json",
    "chars": 2198,
    "preview": "{\n  \"name\": \"redis-store\",\n  \"version\": \"0.0.1\",\n  \"description\": \"\",\n  \"author\": \"\",\n  \"private\": true,\n  \"license\": \"U"
  },
  {
    "path": "examples/redis-store/src/app.controller.ts",
    "chars": 243,
    "preview": "import { Controller, Get, Session } from '@nestjs/common';\n\n@Controller()\nexport class AppController {\n  @Get()\n  getHel"
  },
  {
    "path": "examples/redis-store/src/app.module.ts",
    "chars": 229,
    "preview": "import { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { Session } from './se"
  },
  {
    "path": "examples/redis-store/src/config.module.ts",
    "chars": 192,
    "preview": "import { Module } from '@nestjs/common';\nimport { ConfigService } from './config.service';\n\n@Module({\n  providers: [Conf"
  },
  {
    "path": "examples/redis-store/src/config.service.ts",
    "chars": 297,
    "preview": "import { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class ConfigService {\n  public readonly REDIS_PORT = "
  },
  {
    "path": "examples/redis-store/src/main.ts",
    "chars": 208,
    "preview": "import { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  co"
  },
  {
    "path": "examples/redis-store/src/redis.module.ts",
    "chars": 482,
    "preview": "import { DynamicModule } from '@nestjs/common';\nimport { RedisModule, RedisModuleOptions } from 'nestjs-redis';\nimport {"
  },
  {
    "path": "examples/redis-store/src/session.module.ts",
    "chars": 841,
    "preview": "import * as ConnectRedis from 'connect-redis';\nimport * as session from 'express-session';\nimport { RedisService } from "
  },
  {
    "path": "examples/redis-store/tsconfig.build.json",
    "chars": 97,
    "preview": "{\n  \"extends\": \"./tsconfig.json\",\n  \"exclude\": [\"node_modules\", \"test\", \"dist\", \"**/*spec.ts\"]\n}\n"
  },
  {
    "path": "examples/redis-store/tsconfig.json",
    "chars": 546,
    "preview": "{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecorat"
  },
  {
    "path": "jest.config.js",
    "chars": 283,
    "preview": "module.exports = {\n  moduleFileExtensions: ['js', 'ts'],\n  testRegex: '.spec.ts$',\n  transform: {\n    '^.+\\\\.(t|j)s$': '"
  },
  {
    "path": "package.json",
    "chars": 2163,
    "preview": "{\n  \"name\": \"nestjs-session\",\n  \"version\": \"4.0.0\",\n  \"description\": \"Idiomatic NestJS module for session\",\n  \"main\": \"i"
  },
  {
    "path": "src/index.ts",
    "chars": 1541,
    "preview": "import {\n  AsyncOptions,\n  createModule,\n  SyncOptions,\n} from 'create-nestjs-middleware-module';\nimport expressSession "
  },
  {
    "path": "src/retriesMiddleware.ts",
    "chars": 908,
    "preview": "import { InternalServerErrorException } from '@nestjs/common';\nimport * as express from 'express';\n\ntype WaitingStrategy"
  },
  {
    "path": "tsconfig.build.json",
    "chars": 99,
    "preview": "{\n  \"extends\": \"./tsconfig.json\",\n  \"exclude\": [\"node_modules\", \"dist\", \"__tests__\", \"examples\"]\n}\n"
  },
  {
    "path": "tsconfig.json",
    "chars": 568,
    "preview": "{\n  \"compilerOptions\": {\n    \"lib\": [\"ES2022\"],\n    \"module\": \"node16\",\n    \"target\": \"ES2022\",\n    \"removeComments\": fa"
  }
]

About this extraction

This page contains the full source code of the iamolegga/nestjs-session GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 58 files (58.5 KB), approximately 16.6k tokens, and a symbol index with 43 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!