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

support non-project forms #1

Merged
merged 3 commits into from
Oct 3, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 7 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ import { clientHeader, encode64 } from './utils';
import { Session } from './session';

export interface Config {
projectKey: string;
projectKey?: string;
}

export class Client {
projectKey: string;
projectKey: string | undefined;
private session: Session | undefined;

constructor(config: Config) {
constructor(config: Config = {}) {
this.projectKey = config.projectKey;
if (typeof window !== 'undefined') this.startBrowserSession();
}
Expand Down Expand Up @@ -52,7 +52,9 @@ export class Client {
): Promise<SubmissionResponse> {
let endpoint = opts.endpoint || 'https://formspree.io';
let fetchImpl = opts.fetchImpl || fetchPonyfill({ Promise }).fetch;
let url = `${endpoint}/p/${this.projectKey}/f/${formKey}`;
let url = this.projectKey
? `${endpoint}/p/${this.projectKey}/f/${formKey}`
: `${endpoint}/f/${formKey}`;

const serializeBody = (data: SubmissionData): FormData | string => {
if (data instanceof FormData) return data;
Expand Down Expand Up @@ -92,6 +94,6 @@ export class Client {
/**
* Constructs the client object.
*/
export const createClient = (config: Config): Client => {
export const createClient = (config?: Config): Client => {
return new Client(config);
};
25 changes: 25 additions & 0 deletions test/submitForm.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,31 @@ it('resolves with body and response when successful', () => {
});
});

it('uses the form URL when no project key is provided', () => {
const mockFetch = (url, props) => {
expect(props.method).toEqual('POST');
expect(props.mode).toEqual('cors');
expect(url).toEqual('https://formspree.io/f/xxyyhashid');
return success;
};

return createClient()
.submitForm(
'xxyyhashid',
{},
{
fetchImpl: mockFetch
}
)
.then(({ body, response }) => {
expect(body.id).toEqual('xxx');
expect(response.status).toEqual(200);
})
.catch(e => {
throw e;
});
});

it('uses a default client header if none is given', () => {
const mockFetch = (_url, props) => {
expect(props.headers['Formspree-Client']).toEqual(
Expand Down