Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 🎸 improve yar values and flash typings #169

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions lib/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { Id, PolicyOptions } from '@hapi/catbox';
import { CachePolicyOptions, Plugin, Request, ResponseToolkit, Server, ServerOptionsCache } from '@hapi/hapi';


declare namespace yar {

export interface YarValues {}
export interface YarFlashes {}

type YarValKeys = keyof YarValues;
type YarFlashKeys = keyof YarFlashes;

interface YarOptions {
/**
* Determines the name of the cookie used to store session information.
Expand Down Expand Up @@ -109,20 +117,26 @@ declare namespace yar {
/**
* - assigns a value (string, object, etc) to a given key which will persist across requests. Returns the value.
*/
set<T>(key: string, value: T): T;
set<T extends YarValKeys>(key: T, value: YarValues[T]): YarValues[T];
set<T = unknown>(key: string, value: T): T;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR looks all right, why did you need all those declarations with unknown though?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Marsup this allowed the autocomplete to pick up <T extends YarValKeys>(key: T, value: YarValues[T]) as well as (key: string, value: T), allowing for typed yar values, and also unknown values. Without the <T = unknown>, it wouldn't pick up any types and set values to any. This was the "AHAH!" moment from @kanongil 's comment.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I tend to avoid overloads whenever possible as it makes manipulating types much harder, if there's no other way 🤷🏻‍♂️



/**
* assigns values to multiple keys using each 'keysObject' top-level property. Returns the keysObject.
*/
set<T extends { [key: string]: any }>(keysObject: T): T;
set<T extends Partial<YarValues>>(keysObject: T): T;
set<T = Record<string, unknown>>(keysObject: T): T;

/**
* retrieve value using a key. If 'clear' is 'true', key is cleared on return.
*/
get(key: string, clear?: boolean): any;
get <T extends YarValKeys>(key: T, clear?: boolean): YarValues[T] | null;
get <T = unknown>(key: string, clear?: boolean): T | null;
/**
* clears key.
*/
clear(key: string): void;
clear <T extends YarValKeys>(key: T): void;
clear (key: string): void;
/**
* Manually notify the session of changes (when using get()
* and changing the content of the returned reference directly without calling set()).
Expand All @@ -136,7 +150,10 @@ declare namespace yar {
* 'isOverride' used to indicate that the message provided should replace
* any existing value instead of being appended to it (defaults to false).
*/
flash(type?: string, message?: any, isOverride?: boolean): any[];
flash <T extends YarFlashKeys>(type: T, message: YarFlashes[T], isOverride?: boolean): YarFlashes[T][];
flash <T = unknown>(type: string, message: T, isOverride?: boolean): T[];
flash <T extends YarFlashKeys>(type: T): YarFlashes[T][];
flash <T = YarFlashes>(): { [key in keyof T]: T[key][] };

/**
* if set to 'true', enables lazy mode.
Expand All @@ -160,7 +177,9 @@ declare namespace yar {
revoke(id: Id): Promise<void>;
}
}

declare const yar: Plugin<yar.YarOptions>;

export = yar;

declare module '@hapi/hapi' {
Expand Down
164 changes: 163 additions & 1 deletion test/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,31 @@
import * as lab from '@hapi/lab';
import { Request, Server } from '@hapi/hapi';
import * as yar from '../..';

const { expect } = lab.types;

declare module '../..' {

interface YarValues {

test1: string;
test2: {
a: true;
b: string;
},

example: {
key: string;
};
}

interface YarFlashes {

success: { title: string; message: string; type: 'success' };
error: { title: string; message: string; type: 'error' };
}
}

async function boot() {
const server = new Server();
await server.register({
Expand All @@ -21,10 +46,147 @@ async function boot() {
path: '/test',
method: 'get',
handler(request: Request) {

/** Typed YarValues */
const example = request.yar.get('example');

expect.error(
request.yar.get('test1') === 123
);

const test1 = request.yar.get('test1');
const test2 = request.yar.get('test2');

test1 === '1233';
test2?.a === true;

expect.type<string | null>(test1);
expect.type<{ a: true; b: string } | null>(test2);


/** Untyped YarValues */
const test3 = request.yar.get <{ something: 'else' }>('test3');

expect.type<{ something: 'else' } | null>(test3);

expect.error(
request.yar.get <boolean>('test4') === 123
);


return {
id: request.yar.id,
key: example?.key,
};
},
});

server.route({

path: '/test',
method: 'post',
handler(request: Request) {

/** Typed YarValues */
expect.type<string>(
request.yar.set('test1', '123')
);

expect.error<string>(
request.yar.set('test1', 123)
);

expect.type<yar.YarValues['test2']>(
request.yar.set('test2', {
a: true,
b: '123',
})
);

const partialYarObj = {
test1: '123',
};

expect.type<Partial<yar.YarValues>>(request.yar.set(partialYarObj));

expect.error<Partial<yar.YarValues>>(
request.yar.set({ bad: 'type' })
);


/** Untyped YarValues */

expect.type<{ good: 'type' }>(
request.yar.set({ good: 'type' })
);

expect.type<boolean>(
request.yar.set('anything', true)
);


/** Typed YarFlashes */
expect.type<yar.YarFlashes['error'][]>(

request.yar.flash('error', {
title: 'Error',
message: 'This is an error',
type: 'error'
})
);

expect.type<yar.YarFlashes['success'][]>(
request.yar.flash('success', {
title: 'Success',
message: 'This is a success',
type: 'success'
})
);

expect.error<yar.YarFlashes[yar.YarFlashKeys][]>(
request.yar.flash('info', 'message')
)

expect.type<yar.YarFlashes['error'][]>(
request.yar.flash('error')
)

expect.type<yar.YarFlashes['success'][]>(
request.yar.flash('success')
)

expect.error<yar.YarFlashes['success'][]>(
request.yar.flash('error')
)

expect.type<{ [k in keyof yar.YarFlashes]: yar.YarFlashes[k][] }>(
request.yar.flash()
);

/** Untyped YarFlashes */

expect.type<string[]>(
request.yar.flash('info', 'message')
)


type OtherFlash = {
name: string;
text: string;
}

type CustomFlashes = {

info: OtherFlash
warning: OtherFlash
};

expect.type<{ [key in keyof CustomFlashes]: OtherFlash[] }>(
request.yar.flash <CustomFlashes>()
);

return {
id: request.yar.id,
key: example.key,
};
},
});
Expand Down