How to use the @foal/core.Post function in @foal/core

To help you get started, we’ve selected a few @foal/core examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github FoalTS / foal / packages / acceptance-tests / src / examples / validation-and-sanitization.spec.ts View on Github external
it('Usage with a Hook', () => {
      class SocialPost {

        @Length(10, 20)
        title: string;

        @Contains('hello')
        text: string;

      }

      class SocialPostController {

        @Post()
        @ValidateBodyFromClass(SocialPost, { /* options if relevant */ })
        createSocialPost() {
          // ...
          return new HttpResponseCreated();
        }

      }

      const app = createApp(SocialPostController);

      return request(app)
        .post('/')
        .send({ text: 'foo' })
        .expect(400)
        .expect([
          {
github FoalTS / foal / packages / acceptance-tests / src / openapi.hooks.spec.ts View on Github external
const actualDocument = createOpenApiDocument(ApiController);

    deepStrictEqual(actualDocument, expectedDocument);

    // Test hook conflicts (Two calls of @JWT).

    @ApiInfo({
      title: 'My API',
      version: '1.0.0'
    })
    class ApiController2 {
      @Get('/products')
      @JWTOptional()
      readProducts() {}

      @Post('/products')
      @JWTRequired()
      @ValidateBody({
        properties: {
          name: { type: 'string' }
        },
        type: 'object',
      })
      createProduct() {}
    }

    const yamlDocument2 = readFileSync(join(__dirname, './assets/openapi.hooks2.yml'), 'utf8');
    const expectedDocument2 = parse(yamlDocument2);

    const actualDocument2 = createOpenApiDocument(ApiController2);

    deepStrictEqual(actualDocument2, expectedDocument2);
github FoalTS / foal / packages / acceptance-tests / src / mongoose-db.mongodb-store.spec.ts View on Github external
return new HttpResponseOK();
    }
  }

  class AuthController {
    @dependency
    store: MongoDBStore;

    @Post('/logout')
    @TokenRequired({ store: MongoDBStore, extendLifeTimeOrUpdate: false })
    async logout(ctx: Context) {
      await this.store.destroy(ctx.session.sessionID);
      return new HttpResponseNoContent();
    }

    @Post('/login')
    @ValidateBody({
      additionalProperties: false,
      properties: {
        email: { type: 'string', format: 'email' },
        password: { type: 'string' }
      },
      required: ['email', 'password'],
      type: 'object',
    })
    async login(ctx: Context) {
      const user = await UserModel.findOne({ email: ctx.request.body.email });

      if (!user) {
        return new HttpResponseUnauthorized();
      }
github FoalTS / foal / packages / acceptance-tests / src / authentication / session-token.token.spec.ts View on Github external
@Post('/signup')
    @ValidateBody(credentialsSchema)
    async signup(ctx: Context) {
      const user = new User();
      user.email = ctx.request.body.email;
      user.password = await hashPassword(ctx.request.body.password);
      await getRepository(User).save(user);

      const session = await this.store.createAndSaveSessionFromUser(user);
      return new HttpResponseOK({
        token: session.getToken()
      });
    }

    @Post('/login')
    @ValidateBody(credentialsSchema)
    async login(ctx: Context) {
      const user = await getRepository(User).findOne({ email: ctx.request.body.email });

      if (!user) {
        return new HttpResponseUnauthorized();
      }

      if (!await verifyPassword(ctx.request.body.password, user.password)) {
        return new HttpResponseUnauthorized();
      }

      const session = await this.store.createAndSaveSessionFromUser(user);
      return new HttpResponseOK({
        token: session.getToken()
      });
github FoalTS / foal / packages / acceptance-tests / src / openapi.spec.ts View on Github external
@ApiRequestBody({
      content: {
        '*/*': {
          schema: {
            items: { $ref: '#/components/schemas/User' },
            type: 'array',
          }
        }
      },
      description: 'List of user object',
      required: true
    })
    @ApiResponse('default', { description: 'successful operation', content: {} })
    createUsersWithArrayInput() {}

    @Post('/createWithList')
    @ApiOperation({
      operationId: 'createUsersWithListInput',
      responses: {},
      summary: 'Creates list of users with given input array'
    })
    @ApiRequestBody({
      content: {
        '*/*': {
          schema: {
            items: { $ref: '#/components/schemas/User' },
            type: 'array'
          }
        }
      },
      description: 'List of user object',
      required: true
github FoalTS / foal / packages / cli / src / generate / specs / rest-api / test-foo-bar.controller.ts View on Github external
if (!testFooBar) {
      return new HttpResponseNotFound();
    }

    return new HttpResponseOK(testFooBar);
  }

  @Post('/')
  @ValidateBody(testFooBarSchema)
  async post(ctx: Context) {
    const testFooBar = await getRepository(TestFooBar).save(ctx.request.body);
    return new HttpResponseCreated(testFooBar);
  }

  @Post('/:testFooBarId')
  postById() {
    return new HttpResponseMethodNotAllowed();
  }

  @Patch('/')
  patch() {
    return new HttpResponseMethodNotAllowed();
  }

  @Patch('/:testFooBarId')
  @ValidateParams({ properties: { testFooBarId: { type: 'number' } }, type: 'object' })
  @ValidateBody({ ...testFooBarSchema, required: [] })
  async patchById(ctx: Context) {
    const testFooBar = await getRepository(TestFooBar).findOne(ctx.request.params.testFooBarId);

    if (!testFooBar) {
github FoalTS / foal / packages / acceptance-tests / src / authentication / session-token.cookie.redirection.spec.ts View on Github external
if (!user) {
        return new HttpResponseRedirect('/login');
      }

      if (!await verifyPassword(ctx.request.body.password, user.password)) {
        return new HttpResponseRedirect('/login');
      }

      const session = await this.store.createAndSaveSessionFromUser(user);
      const response = new HttpResponseRedirect('/home');
      const token = session.getToken();
      setSessionCookie(response, token);
      return response;
    }

    @Post('/logout')
    @TokenRequired({
      cookie: true,
      extendLifeTimeOrUpdate: false,
      redirectTo: '/login',
      store: TypeORMStore,
    })
    async logout(ctx: Context) {
      await this.store.destroy(ctx.session.sessionID);
      const response = new HttpResponseRedirect('/login');
      removeSessionCookie(response);
      return response;
    }

    @Get('/home')
    @TokenRequired({ store: TypeORMStore, cookie: true, redirectTo: '/login' })
    home() {
github FoalTS / foal / packages / acceptance-tests / src / csrf / spa-and-api.stateful.spec.ts View on Github external
const session = await this.store.createAndSaveSessionFromUser({ id: 1 }, { csrfToken: true });

      const response = new HttpResponseOK();
      setSessionCookie(response, session.getToken());
      setCsrfCookie(response, await getCsrfToken(session));
      return response;
    }
  }

  @TokenRequired({
    cookie: true,
    store: TypeORMStore,
  })
  @CsrfTokenRequired()
  class ApiController {
    @Post('/products')
    createProduct() {
      return new HttpResponseCreated();
    }
  }

  class AppController {
    subControllers = [
      AuthController,
      controller('/api', ApiController),
    ];
  }

  before(async () => {
    process.env.SETTINGS_SESSION_SECRET = 'session-secret';
    await createConnection({
      database: 'e2e_db.sqlite',
github FoalTS / foal / packages / acceptance-tests / src / authentication / jwt.cookie.spec.ts View on Github external
@ValidateBody(credentialsSchema)
    async login(ctx: Context) {
      const user = await getRepository(User).findOne({ email: ctx.request.body.email });

      if (!user) {
        return new HttpResponseUnauthorized();
      }

      if (!await verifyPassword(ctx.request.body.password, user.password)) {
        return new HttpResponseUnauthorized();
      }

      return this.generateLoginResponse(user);
    }

    @Post('/logout')
    @JWTRequired({ cookie: true })
    async logout() {
      return new HttpResponseNoContent()
        .setCookie(
          Config.get('settings.jwt.cookieName', 'auth'),
          '',
          { ...cookieOptions, maxAge: 0 }
        );
    }

    private async generateLoginResponse(user: User): Promise {
      const payload = {
        email: user.email,
        id: user.id,
      };
github FoalTS / foal / packages / typeorm / e2e / upload-and-download.spec.ts View on Github external
class UploadedFile extends BaseEntity {

      @PrimaryGeneratedColumn()
      id: number;

      @Column()
      path: string;

      @ManyToOne(type => User)
      user: User;

    }

    class AppController {

      @Post('/upload')
      async upload(ctx: Context) {
        const form = new IncomingForm();
        form.uploadDir = 'uploaded';
        form.keepExtensions = true;
        const { files } = await parseForm(form, ctx);

        const file = new UploadedFile();
        file.user = user;
        file.path = files.file1.path;
        await file.save();

        return new HttpResponseOK();
      }

      @Get('/download')
      async download() {