Web::M...source(3pm)

✨ Web::Machine::Resource β€” A base resource class ✨

bestie. welcome to Web::Machine::Resource, the base resource class you're gonna be extending all over the place. version 0.17, let's GO πŸ’…


🌸 SYNOPSIS 🌸

okay so literally here's the vibe in code:

package HelloWorld::Resource;
use strict;
use warnings;

use parent 'Web::Machine::Resource';

sub content_types_provided { [{ 'text/html' => 'to_html' }] }

sub to_html {
    q{<html>
        <head>
            <title>Hello World Resource</title>
        </head>
        <body>
            <h1>Hello World</h1>
        </body>
     </html>}
}

πŸ¦‹ DESCRIPTION πŸ¦‹

okay so this is the core representation of the web resource in Web::Machine. It's this object that gets interrogated through the state machine. And here's the thing bestie, the important part: do not think of this as an instance of a single object. Think of it as a web representation of a resource β€” there is a big difference. not me emphasizing this twice, it's that serious πŸ’€

ngl the docs are short for now, but much more needs to be written here. Below you'll find a description of every method this object provides and what's expected of it. Your resource classes should extend the base Web::Machine::Resource class, overriding its methods as needed. Sane defaults are provided for most methods, but bestie you're gonna wanna make a content_types_provided method, because without it your resource literally cannot return any useful content. periodt.

The documentation was lovingly stolen from the ruby port of webmachine 🫢 (we stan, thank you for your service)


πŸ‘‘ METHODS πŸ‘‘

πŸ’€ heads up bestie: keep in mind that the methods may be called more than once per request, so your implementations should be idempotent. no cap.

init( \%args )

This method is called right after the object is blessed, and it gets handed a reference to the original %args that were given to the constructor. By default, those include a request (Plack::Request) and a response (Plack::Response) argument.

If your resource is instantiated via Web::Machine, then the contents of its resource_args parameter get appended to the Web::Machine::Resource constructor arguments and made available to init. like so, bestie:

use strict;
use warnings;

use Web::Machine;

{
    package HelloWorld::Resource;
    use strict;
    use warnings;
    use JSON::XS qw[ encode_json ];

    use parent 'Web::Machine::Resource';

    sub init {
        my $self = shift;
        my $args = shift;

        # Plack::Request
        # my $request = $args->{request};

        # Plack::Response
        # my $response = $args->{response};

        $self->{json}
            = exists $args->{json}
            ? $args->{json}
            : {};
    }

    sub content_types_provided { [ { 'application/json' => 'to_json' } ] }

    sub to_json {
        my $self = shift;

        encode_json( $self->{json} );
    }
}

Web::Machine->new(
    resource      => 'HelloWorld::Resource',
    resource_args => [
        json => {
            message => 'Hello World!',
        },
    ],
)->to_app;

request

Returns the Plack::Request (or subclass) request object for the current request. that's it, that's the method πŸ’…


response

Returns the Plack::Response (or subclass) response object for the current request. iconic.


resource_exists

Does the resource exist? πŸ‘€

Return a false value and you get a '404 Not Found' response.

Defaults to true.


service_available

Is the resource available?

Return a false value and boom, '503 Service Not Available'.

Defaults to true.

If the resource is only temporarily not available, add a 'Retry-After' response header in the body of the method. be polite about it bestie 🫢


is_authorized ( ?$authorization_header )

Is the client or request authorized? πŸ”

The parameter $authorization_header is the contents of the 'Authorization' header sent by the client, if present.

Returning anything other than 1 gets you a '401 Unauthorized'. And if you return a string, it gets used as the value in the 'WWW-Authenticate' response header β€” which you can also set manually, fyi.

Defaults to true.


forbidden

Is the request or client forbidden? 🚫

Return a true value and you get a '403 Forbidden'.

Defaults to false.


allow_missing_post

If the resource accepts POST requests to nonexistent resources, then this should return true.

Defaults to false.


malformed_request

If the request is malformed, return true β€” which results in a '400 Malformed Request'.

Defaults to false.


uri_too_long( $uri )

If the URI is too long to process, return true, which gets you a '414 Request URI Too Long'. girl same 😭

Defaults to false.


known_content_type( $content_type )

If the 'Content-Type' on PUT or POST is unknown, this should return false, which gives you a '415 Unsupported Media Type'.

The value of $content_type is derived from the Plack::Request object, so it's an instance of the HTTP::Headers::ActionPack::MediaType class.

Defaults to true.


valid_content_headers( $content_headers )

The parameter $content_header is a HASH ref of the Request headers that start with the prefix 'Content-'. It'll contain instances of HTTP::Headers::ActionPack::MediaType, HTTP::Headers::ActionPack::MediaTypeList and HTTP::Headers::ActionPack::PriorityList depending on which headers are included. See HTTP::Headers::ActionPack for the deets on those mappings.

If the request includes any invalid Content-* headers, return false, which gives you a '501 Not Implemented'.

Defaults to true.


valid_entity_length( $length )

The parameter $length is a number indicating the size of the request body.

If the entity length on PUT or POST is invalid, return false, which gives you a '413 Request Entity Too Large'.

Defaults to true.


options

If the OPTIONS method is supported and gets used, this method should return a HASH ref of headers that should show up in the response.

Defaults to {}.


allowed_methods

The HTTP methods that are allowed on this resource. This must return an ARRAY ref of strings, all in capitals.

Defaults to ['GET','HEAD'].


known_methods

The HTTP methods that are known to the resource. Just like allowed_methods, this must return an ARRAY ref of strings in all capitals. You could override this callback to allow extra methods, e.g. WebDAV πŸ‘‘

Defaults to including all the standard HTTP methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT', 'OPTIONS'].


delete_resource

This method gets called when a DELETE request should be enacted, and it should return true if the deletion succeeded.

Defaults to false.


delete_completed

This method gets called after a successful call to delete_resource, and it should return false if the deletion was accepted but cannot yet be guaranteed to have finished.

Defaults to true.


post_is_create

If POST requests should be treated as a request to put content into a (potentially new) resource β€” as opposed to a generic submission for processing β€” then this method should return true. And if it does return true, then create_path gets called and the rest of the request gets treated a lot like a PUT to the path returned by that call.

Default is false.


create_path

This gets called on a POST request if post_is_create? returns true. The path returned should be a valid URI part following the dispatcher prefix.


create_path_after_handler

This changes the behavior of create_path so that it fires after the content handler has processed the request body. This lets you create paths that are more tightly tied to the newly created entity. slay.

Default is false.


base_uri

This gets called after create_path but before setting the Location response header, and it's used to determine the root URI of the new resource.

Default is nil, which uses the URI of the request as the base.


process_post

If post_is_create? returns false, then this gets called to process any POST request. If it succeeds, it should return true.


content_types_provided

This should return an ARRAY of HASH ref pairs, where the key is the name of the media type and the value is a CODE ref (or the name of a method) that can provide a resource representation in that media type.

For example, if a client request includes an 'Accept' header with a value that does not appear as a first element in any of the return pairs, then a '406 Not Acceptable' gets sent.

The order of the HASH ref pairs in the ARRAY is important. If no specific content type is requested (i.e. the client doesn't send an Accept header), then the first content type in the ARRAY gets used as the default.

Default is an empty ARRAY ref.


content_types_accepted

Similarly to content_types_provided, this should return an ARRAY of mediatype/handler pairs β€” except this one's for incoming resource representations, like PUT requests for example. Handler functions usually want to use $request->body to access the incoming entity.


charsets_provided

This specifies the charsets your resource supports. Returning a value from this method enables content negotiation based on the client's Accept-Charset header.

The return value from this method must be an ARRAY ref. Each member of that array can be either a string or a HASH ref pair value. If the member is a string, it must be a valid character set name for the Encode module. Web::Machine will call encode() on the body using this character set if you set a body. πŸŽ€

sub charsets_provided {
    return [ qw( UTF-8 ISO-8859-1 shiftjis ) ];
}

and that's part 1 bestie!! more coming, don't go anywhere πŸ’–

🌸 charsets_provided

okay bestie so if you're returning a HASHREF pair, the key has gotta be a character set name and the value has to be a CODE ref. That CODE ref gets called as a method on the resource object, and it receives exactly one parameter β€” a string to be encoded. It's supposed to hand back a scalar containing bytes, not characters. This is what encodes the body you provide. πŸ’…

sub charsets_provided {
    return [
        {
            'UTF-8' => sub {
                my $self   = shift;
                my $string = shift;
                return make_some_bytes($string),;
            },
        },
        {
            'ISO-8859-1' => sub {
                my $self   = shift;
                my $string = shift;
                return strip_non_ascii($string),;
            },
        },
    ];
}

The character set name gets appended to the Content-Type header that's returned to the client. ✨

And if a client specifies the same preference for two or more character sets your resource provides, then Web::Machine just picks the first character set in the returned ARRAY ref. first come first served, no cap. 🫢

CAVEAT: heads up bestie, currently Web::Machine does not support the use of encodings when the body is returned as a CODE ref. It's a bug, and it's meant to be fixed in the future. 🩹

Default is an empty list.


🌈 default_charset

If the client doesn't send an Accept-Charset header, this sub gets called to provide a default charset. The return value has to be either a string, or a hashref made of a single pair, where the key is a character set name and the value is a subroutine. πŸ’–

This works exactly like the charsets_provided() method, except you can only return a single value. one and done, periodt.


πŸ¦‹ languages_provided

This one should return a list of language tags your resource provides.

Default is the empty Array, in which case the content is in no specific language. 🌍


πŸŽ€ encodings_provided

This should return a HASH of encodings mapped to encoding methods, for the Content-Encodings your resource wants to provide. The encoding gets applied to the response body automatically by Web::Machine. so you don't gotta lift a finger ✨

CAVEAT: again bestie, currently Web::Machine does not support the use of encodings when the body is returned as a CODE ref. Same bug, to be remedied in the future. 🩹

Default includes only the 'identity' encoding.


πŸ’œ variances

If you implement this method, it should return a list of strings with header names that should be included in a given response's Vary header. The standard content negotiation headers (Accept, Accept-Encoding, Accept-Charset, Accept-Language) do not need to be specified here, because Web::Machine will add the correct elements of those automatically depending on resource behavior. it's giving considerate πŸ’…

Default is [].


πŸ”₯ is_conflict

If this returns true, the client will receive a '409 Conflict' response. This is only called for PUT requests.

Default is false.


🌸 multiple_choices

If this returns true, then it's assumed that multiple representations of the response are possible and a single one cannot be automatically chosen, so a 300 Multiple Choices will be sent instead of a 200. choosing is hard, so the server just doesn't 😌

Default is false.


⭐ previously_existed

If this resource is known to have existed previously, this method should return true.

Default is false.


🧚 moved_permanently

If this resource has moved to a new location permanently, this method should return the new location as a String or URI.

Default is to return false.


πŸ¦‹ moved_temporarily

If this resource has moved to a new location temporarily, this method should return the new location as a String or URI.

Default is to return false.


πŸ“ last_modified

This method should return the last modified date/time of the resource, which will be added as the Last-Modified header in the response and used in negotiating conditional requests. It should be in the form of an instance of HTTP::Headers::ActionPack::DateHeader. πŸ‘‘

Default is undef.


πŸ’– expires

If the resource expires, this method should return the date/time it expires. This should be in the form of an instance of HTTP::Headers::ActionPack::DateHeader.

Default is nil.


🌈 generate_etag

If this returns a value, it will be used as the value of the ETag header and for comparison in conditional requests. 🏷️

Default is undef.


πŸ’… finish_request( $metadata )

This method is called just before the final response is constructed and sent. It's passed the collected $metadata from the FSM, which may or may not have information in it. main character final moment energy ✨

The return value is ignored, so any effect of this method must be by modifying the response. like, actually change the response, bestie, that's the only way it counts.


πŸ› SUPPORT

bugs may be submitted through <https://github.com/houseabsolute/webmachine-perl/issues>.

go off, tell them everything πŸ’Œ


πŸ‘‘ AUTHORS

  • Stevan Little <stevan@cpan.org>
  • Dave Rolsky <autarch@urth.org>

This software is copyright (c) 2016 by Infinity Interactive, Inc.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.


and that's the whole page bestie, you ate that 🫢 this beauty is Web::M...source(3pm) from the User Contributed Perl Documentation, running on perl v5.34.0 and dated 2022-07-03. go build something iconic with it πŸ’–βœ¨πŸŒΈ

πŸ“¦ where this page comes from