Giter VIP home page Giter VIP logo

prismic-client's Introduction

@prismicio/client

npm version npm downloads Github Actions CI Codecov Conventional Commits License

The official JavaScript + TypeScript client library for Prismic.

  • Query content from a Prismic repository.
  • Refines queries using Filters.
  • Automatically query draft content during preview sessions.
  • Built for browser and server usage.
import * as prismic from "@prismicio/client";

// Create a client
const client = prismic.createClient("my-repository");

// Then query for your content
const blogPosts = await client.getAllByType("blog_post");

Install

npm install @prismicio/client

Documentation

To discover what's new on this package check out the changelog. For full documentation, visit the official Prismic documentation.

Contributing

Whether you're helping us fix bugs, improve the docs, or spread the word, we'd love to have you as part of the Prismic developer community!

Asking a question: Open a new topic on our community forum explaining what you want to achieve / your question. Our support team will get back to you shortly.

Reporting a bug: Open an issue explaining your application's setup and the bug you're encountering.

Suggesting an improvement: Open an issue explaining your improvement or feature so we can discuss and learn more.

Submitting code changes: For small fixes, feel free to open a pull request with a description of your changes. For large changes, please first open an issue so we can discuss if and how the changes should be implemented.

For more clarity on this project and its structure you can also check out the detailed CONTRIBUTING.md document.

License

   Copyright 2013-2023 Prismic <[email protected]> (https://prismic.io)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

prismic-client's People

Contributors

angeloashmore avatar ansidev avatar arnaudlewis avatar denisyilmaz avatar dependabot[bot] avatar gholgot avatar hypervillain avatar idlefingers avatar josepjaume avatar kmein avatar levimykel avatar lihbr avatar louisefindlay23 avatar luxcem avatar marcmcintosh avatar maxcelima avatar mccare avatar nsivertsen avatar olegcherr avatar pandicornzombie avatar petetnt avatar phillysnow avatar raph22 avatar rvieceli avatar sarunast avatar srenault avatar tornqvist avatar veloce avatar xrutayisire avatar yimiprod avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prismic-client's Issues

Escape quote from text

Hi,

It looks like double quote (") are not escaped correctly when you use RichText.asHtml(), in my case it duplicates the content.

Images with "ß" in their file name result in "403 Forbidden"

When uploading an Image to the Media Library which contains the character ß in its file name, the image can not be loaded properly.

Repository-Privacy settings do not affect the issue.

Example response when loading the image from S3:

<?xml version="1.0" encoding="UTF-8"?>
<Error>
    <Code>AccessDenied</Code>
    <Message>Access Denied</Message>
    <RequestId>ED58F636AF35D6AA</RequestId>
    <HostId>WxVXqhP+1mTWGa/4QkwJur5fNGThGtr2GlCY1y/xgRsphRgKnXsSVY+GDHPQ9hyEuxsdJ9huiqQ</HostId>
</Error>

Steps to reproduce:

  • Upload image file with "ß" in file name
  • Create a content object containing the image
  • Try to load it via the provided S3-URL

Cache timing

Can I change LRU cache timing?
I can't find the option...

Output tree-shakeable module

Currently, the build output is a single 32KB UMD bundle. Even if an app only does basic document fetches, it's forced to include everything else in its bundle as well.

Please consider also exporting an ES6 module in the package.module field.

Random 404 Error

Decided to work on my app today and got this...
I can still fetch the data fine which confuses me even more
Screenshot 2019-03-10 at 21 11 16

Cache not working?

I am having issues with the cache, it doesnt seem to work.

Prismic.api('website.com').then(api => {
  api.get().then(() => {
    api.get().then(() => {
      api.get().then(() => {
           // Triggers 4 requests
       })
     })
   })
})

Update certain Date & Time Predicates to accept strings

The following Date & Time Predicates need to be updated so they accept a string:

  • dateBefore, dateAfter, & dateBetween need to be able to accept a string of format "YYYY-MM-DD"
  • dayOfWeek, dayOfWeekAfter, & dayOfWeekBefore need to be able to accept a string like "mon" or "tuesday"

Prismic IO library not working in Angular 6 Project

I am facing an error with Prismic IO library after upgrading my Angular project from v5.2.0 to v6.1.1. The error is as below

ERROR in ./node_modules/prismic.io/lib/requests.js
Module not found: Error: Can't resolve 'http' in '/Users/abbas/Development/sobeers/node_modules/prismic.io/lib'
ERROR in ./node_modules/prismic.io/lib/requests.js
Module not found: Error: Can't resolve 'https' in '/Users/abbas/Development/sobeers/node_modules/prismic.io/lib'

Content Relationship and Multi-languages: Wrong type for custom types

Setup:

  • "prismic-javascript": "^1.1.5",
  • Two custom types (home_page and tip). tip is used in a slice of home_page
  • Master language is de-ch and a 2nd language fr-ch

If I query the master language the custom types in slice.items is correct ("type": "tip",)

JS:

  const client = await Prismic.api(`https://${repositoryName}.prismic.io/api/v2`, { accessToken })
  const response = await client.query("", {lang: "de-ch"})

Result

{
  "id": "XKXobhAAAJmVNCNu",
  "type": "home_page",
  "lang": "de-ch",
  "data": {
     ...
    "body": [
      {
        "slice_type": "content",
        "items": [
          {
            "tip": {
              "id": "XKbxCxMAACIAP_bb",
              "type": "tip",
              "lang": "de-ch"
            }
          }
        ]
      }
    ]
  }
}

But when I query a non-master language I get "type": "home_page", as type for the custom type

JS:

  const client = await Prismic.api(`https://${repositoryName}.prismic.io/api/v2`, { accessToken })
  const response = await client.query("", {lang: "fr-ch"})

Result

    {
      "id": "XKXzwxAAAByKNFXn",
      "type": "home_page",
      "lang": "fr-ch",
      "data": {
       ...
        "body": [
          {
            "slice_type": "content",
            "slice_label": null,
            "items": [
              {
                "tip": {
                  "type": "home_page",
                  "lang": "fr-ch",
                 }
              }
            ]}
        ]
      }
    },

Any idea why?

Thanks!

First option in a dropdown always returns null

Quering the first option in a dropdown always returns null. In the pic below if I query and Commercial is selected it returns null, otherwise if any other field is selected it returns that field. I also fetch my data and passed the empty string in my query to fetch all fields and reproduce the same error.
screen shot 2018-05-15 at 3 47 02 pm

Querying by document.type returns records from all types

Using this lib at "prismic-javascript": "^1.0.5"

Here's my express request route:

const PrismicJS = require('prismic-javascript');
const prismic = PrismicJS.api('https://foo.prismic.io/api');
const { Predicates } = PrismicJS;

  router.get('/paintings', (req, res) => {
    prismic.then((api) => {
      return api.query(Predicates.at('document.type', 'painting'));
    }).then((paintings) => {
      res.json(paintings);
    }, (err) => {
      res.status(err.statusCode || 500).json(err);
    });
  });

For some reason this request returns records from every document type in my project. Not sure if this is an issue with this library or with prismic.io's API itself, but it's a breaking bug.

Unable to encode .... of type object - Prismic.Predicate.at()

Hello,

I've tried to use multiple predicates on a query as the example but when the code (see below) is executed I got an error: Unable to encode no-case-study of type object

const noCasesStudiesProjects = client().then(api => {
    return api
      .query([
        Prismic.Predicates.at('document.type', 'project'),
        Prismic.Predicates.at('document.tags', ['no-case-study'])
      ])
      .then(data => {
        return data.results;
      });
  });

I'm using : Nuxt 2.0.0 and prismic-javascript ^2.0.1

Any ideas ?
Thanks

NB : Until yesterday, everything worked well :/
NB2 : Seems to works in build and generate (nuxt) process 🧐

API values not in camelcase

Values returned from the API are not in camelcase. Expected myTitleField to be returned but instead received my_title_field. This becomes an issue when working with ESlint as I have to fully disable the camelcase rule. Assuming there is no option of changing/ editing how data comes back from the API?

I keep getting this CORS issue

I just released my website and I keep getting this CORS issue from prismic. I don't know where to turn for this.

Any idea?

Failed to load https://automate-your-brand.prismic.io/app/authenticated/v2: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://automateyourbrand.com' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

The options variable is changed after calling a query

After you've called a query using this kit, the options variable is changed and cannot be re-used. Is this done on purpose?

For example, the second query here does not work because the options variable is changed after running the first query.

const options = { lang: 'fr-fr' }
const home = await api.getSingle('homepage', options)
const layout = await api.getSingle('layout', options)

But this one does work:

const options1 = { lang: 'fr-fr' }
const home = await api.getSingle('homepage', options1)
const options2 = { lang: 'fr-fr' }
const layout = await api.getSingle('layout', options2)

api.getByUID returns unexpected 400

Hey,
I use the function: api.getByUID(type, uid)and get the following crash message:

Unexpected status code [400] on URL [...] (my.text-content.uid%2C%20%22kontakt%22)%5D%5D

UID and type are defined on prismic, I double-checked.

Cheers,
Alex

Add a Uid/Slug field when creating new slice

Please add a Uid or Slug field for each slices in the beta builder. The slug should set the object name in the JSON object.

At the moment there is no way other than manually change the JSON object name.

image

UnhandledPromiseRejectionWarning

Not sure if this is the lib error, or my code.

Express controller code:

router.get('/', (req, res, next) => {
  return req.prismic.api
    .query('')
    .then((posts) => {
      res.render('blog/index', {
        title: 'Blog',
        posts: posts
      })
    })
    .catch(next)
})

Now, disable connection on the computer and try to access the route:

(node:8251) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): FetchError: request to http://foo.prismic.io/api?access_token=... failed, reason: getaddrinfo ENOTFOUND foo.prismic.io foo.prismic.io:80

(node:8251) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

CORS issue on chrome

Hi, we are using the prismic platform to supply our application with content. This content also has 3D images which we need to load in a react component. However when we try this we always get the CORS error:

Access to fetch at 'https://sales-tool-vdv-antwerpen.cdn.prismic.io/sales-tool-vdv-antwerpen/d19dd7e73958894738b4ae422d02a0d8ab3d2e79_n1-balkon-naar-receptie.jpg' from origin 'https://playground.codecliff.be' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

This while when we use the url inside an ´a´ tag it is fine and loads fine. Only when we try to use it in another component which calls the URL I guess it doesn't work.

This issue only shows on chrome (not on safari, edge or firefox) which makes it very critical. For now we are looking into working with a proxy but to be honest it should be possible to add a ´Access-Control-Allow-Origin´ header to the response of those assets.

Consider removing polyfills

Maybe, for the upcoming 2.0 release, one could consider removing the fetch and Promise polyfills from prismic-javascript. They account for almost half of the bundle size. Both fetch and Promise have pretty good browser support by now, and most apps already have some kind of polyfill strategy in place (e.g. polyfill.io), meaning users are forced to download polyfills twice in many cases.

Shared cache

My express server requests a lot of content from prismic which doesn’t change very often. Is it possible to share the cache between individual requests? I want to still be able to pass the req object into a new prismic client on each request to ensure preview and experiments keep working as expected

404 status on getApi

Hi,

I have a trouble with my prismic api, on my ionic 3 project.
Everything was working well with the 'prismic.io' version of the npm, but now I have a 404 error. So I decided to migrate to the new 'prismic-javascript' api. I ot the 2 npms, did the types config in package.json and include the Prismic object with :
import Prismic from 'prismic-javascript';

here is my code :

Prismic.getApi(api_v2, { }).then(function(api) {
	console.log('GOT API : ', api);
	return api.query( [Prismic.Predicates.at("document.type", model), Prismic.Predicates.dateAfter('document.last_publication_date', date)], {} );
}).then(function(response) {
	console.log("Documents: ", response.results);
}, function(err) {
	console.log("Something went wrong: ", err);
});

I always get a 404 error. I never get the console log. I tried several API endpoint like :
let api_v2 = 'https://[my-repo].cdn.prismic.io/api/v2';
let api_v2 = 'https://[my-repo].prismic.io/api/v2';
let api_v2 = 'http://[my-repo].prismic.io/api/v2';
let api_v2 = 'https://[my-repo].prismic.io/api';
let api_v2 = 'http://[my-repo].prismic.io/api';

Every time I get this 404 error :

Failed to load resource: the server responded with a status of 404 (Not Found)
11:33:26.168 main.js:6209 Something went wrong:  Error: Unexpected status code [404] on URL https://[my-repo].cdn.prismic.io/api/v2
    at vendor.js:128015
    at t.invoke (polyfills.js:3)
    at Object.onInvoke (vendor.js:5085)
    at t.invoke (polyfills.js:3)
    at r.run (polyfills.js:3)
    at polyfills.js:3
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (vendor.js:5076)
    at t.invokeTask (polyfills.js:3)
    at r.runTask (polyfills.js:3)

Any idea ?
Thanks !

api.getByIDs return 400 HTTP code

Hi,

I use the getByIDs query helper for get some content, but the API return an 400.

{
  "name": "prismic-request-error",
  "message": "Unexpected status code [400] on URL https://my-awesome-repository.prismic.io/api/v2/documents/search?page=1&pageSize=3&lang=*&ref=PAGEID&q=%5B%5B%3Ad%20%3D%20in(document.id%2C%20%5BXXXX%2CYYYY%5D)%5D%5D",
  "status": 400
}

This is the return of api

{
  "message": "`]' expected but `[' found on line:1 col:2 in query '[[:d = in(document.id, [XXXX,YYYY])]]'\n[[:d = in(document.id, [XXXX,YYYY])]]\n ^\n",
  "type": "parsing-error",
  "line": 1,
  "column": 2,
  "id": 0,
  "location": "query"
}

The bug seems to be about the code, because I can make two separate calls with getByID.

I think the bug is about this line :
https://github.com/prismicio/prismic-javascript/blob/master/src/api.ts#L626

And maybe about the predicates function :
https://github.com/prismicio/prismic-javascript/blob/master/src/predicates.ts#L52

(the ids are replaced by XXXXand YYYY in code)

cc: @Duaner

Request pending

Hello,

I'm trying this module for the API v2 but when I try to call api.getByUID, the request is blocked on pending.

I think the API v2 is enabled on my repo because we can reach this url .

I tried the Node.js demo by replacing the endpoint to mine, I got the same result.

Have you got an idea about this ?

Thanks for your help.

Publish typings for prismic-javascript.

We're using Prismic in a new React/TS project and noticed that this library is written in Typescript too. Unfortunately, none of the types are exported.

Could we export some types to DefinitelyTyped? We would be happy to beta test this library going forward.

set timeout

Hi,
Sometimes, data query takes too long, how can i set a timeout value ?

Ability to create a standard component using JSON

Right now I am adding labels to all my RichText editors

labels: ["blockquote"]

But because we cannot save it as a custom component, I'll have to manually add the same code above to all the RichText JSON object.

Any idea if this is in the roadmap or not?

v1.5 doesn't allow preview of unpublished files / changes

When additional credentials are not supplied v1.5 doesn't allow preview of unpublished pages, and shows only the currently published version when previewing pages which have changes.

I think that this is a bug because the token supplied by the preview page should take precedence over any global credentials. When using the token supplied I should always be able to get the specified page in its current state.

In the previewSession method:

previewSession(token: string, linkResolver: (doc: any) => string, defaultUrl: string, cb?: RequestCallback<string>): Promise<string> {
  return this.httpClient.request<PreviewResponse>(token).then((result) => {
    // ...
      return this.getByID(result.mainDocument).then((document) => {
        if (!document) {
          cb && cb(null, defaultUrl);
          return defaultUrl;
        } else {
          const url = linkResolver(document);
          cb && cb(null, url);
          return url;
        }
      });
    //...
  })
  //...
}

The initial previewSession request with the supplied token returns the correct document ID in result.mainDocument, but then this ID is fed into getByID which uses queryFirst/query. In the query method, the ref property in the options is set to this.masterRef.ref, which is the resolved document ID, but the query returns nothing if the page is not published, or the current-published state of the page for a published page, but not it's updates.

If this is a bug, a working solution is to add an options object to the getByID call with the ref property set to the token, eg:

return this.getByID(result.mainDocument, {ref: token})

In the previous version of previewSession, this was the case:

previewSession(token: string, ...) {
  api.requestHandler.request(token, function(err: Error, result: any, xhr: any) {
    // ...
    api.everything().query(Predicates.at("document.id", mainDocumentId)).ref(token).lang('*').submit()
    // ... 
  })
}

I will also raise a pull request referencing this issue.

Provide better Typescript definition files

Hi Prismic folks :)

I'm trying to use the nodejs package with its bundled d.ts files.
However, types are not properly imported when using the module.
It comes from several facts:

  • First, this comes from the way the module is declared, ie. using a namespace. declare namespace Prismic {...} & export = Prismic;. Only what is in the namespace is visible if i'm not mistaken.
  • As a library, the barel file (index.d.ts) should re-export all public APIs. When fetching the api object with Prismic.getApi(...), I cannot write the proper response type since the PrismicApi type is hidden in the namespace.

It could be better to change the namespace to a plain object while re-exporting all sub modules. This way, both the Prismic object and all APIs are visible.

Last but not the least, a little quote from the TS documentation :

Exporting a namespace from your module is an example of adding too many layers of nesting. While namespaces sometime have their uses, they add an extra level of indirection when using modules. This can quickly become a pain point for users, and is usually unnecessary.

What do you guys think ?

fetch is not defined

Opening this issue on behalf of a client.

import Prismic from'prismic-javascript';



getComponents = ()=>{

let { cookies } = this.props;

Prismic.api(apiEndpoint).then(api => {

api.query(Prismic.Predicates.at('document.type', 'landingpage')).then(response => {

if(response) {

if(Cookies){

let res = response.results[0].data;

console.log(res);

}

}

});

}

On localhost everything works fine. But I get the is error on Heroku.

UnhandledPromiseRejectionWarning: ReferenceError: fetch is not defined

(node:22) UnhandledPromiseRejectionWarning: ReferenceError: fetch is not defined
2019-01-16T14:36:21.424550+00:00 app[web.1]: at /app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:15368
2019-01-16T14:36:21.424553+00:00 app[web.1]: at r (/app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:15723)
2019-01-16T14:36:21.424554+00:00 app[web.1]: at e.request (/app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:15909)
2019-01-16T14:36:21.424556+00:00 app[web.1]: at e.request (/app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:18769)
2019-01-16T14:36:21.424557+00:00 app[web.1]: at /app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:19012
2019-01-16T14:36:21.424558+00:00 app[web.1]: at e.get (/app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:18207)
2019-01-16T14:36:21.424559+00:00 app[web.1]: at /app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:18984
2019-01-16T14:36:21.424561+00:00 app[web.1]: at /app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:19089
2019-01-16T14:36:21.424563+00:00 app[web.1]: at new Promise (<anonymous>)
2019-01-16T14:36:21.424565+00:00 app[web.1]: at e.cachedRequest (/app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:18918)
2019-01-16T14:36:21.424566+00:00 app[web.1]: at e.get (/app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:4960)
2019-01-16T14:36:21.424567+00:00 app[web.1]: at Function.e.getApi (/app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:20826)
2019-01-16T14:36:21.424569+00:00 app[web.1]: at t (/app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:20983)
2019-01-16T14:36:21.424570+00:00 app[web.1]: at Object.e.api (/app/build/static/node_modules/prismic-javascript/dist/prismic-javascript.min.js:1:21244)
2019-01-16T14:36:21.424571+00:00 app[web.1]: at t.n.getComponents (/app/build/static/js/components/Topbar/Topbar.js:109:13)
2019-01-16T14:36:21.424573+00:00 app[web.1]: at t.value (/app/build/static/js/components/Topbar/Topbar.js:88:10)
2019-01-16T14:36:21.424574+00:00 app[web.1]: at /app/build/static/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:27:128
2019-01-16T14:36:21.424576+00:00 app[web.1]: at m (/app/build/static/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:28:411)
2019-01-16T14:36:21.424577+00:00 app[web.1]: at e.render (/app/build/static/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:33:16)
2019-01-16T14:36:21.424578+00:00 app[web.1]: at e.read (/app/build/static/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:32:201)
2019-01-16T14:36:21.424580+00:00 app[web.1]: at Object.renderToString (/app/build/static/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:41:1)
2019-01-16T14:36:21.424582+00:00 app[web.1]: at L (/app/build/static/js/app.js:103:31)
2019-01-16T14:36:21.424584+00:00 app[web.1]: at Object.exports.render (/app/server/renderer.js:95:26)
2019-01-16T14:36:21.424585+00:00 app[web.1]: at dataLoader.loadData.then.preloadedState (/app/server/index.js:203:29)
2019-01-16T14:36:21.424587+00:00 app[web.1]: at <anonymous>
2019-01-16T14:36:21.424588+00:00 app[web.1]: at process._tickDomainCallback (internal/process/next_tick.js:228:7)
2019-01-16T14:36:21.424782+00:00 app[web.1]: (node:22) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

Querying document fields "function at(..)] unexpected field"

Hello,

I've just started using the prismic API to start building a blog on my company's website, however when testing out the API via the documentation, I'm running into an exception from the API.

Whenever I run a query to filter by a specific field for a document type, e.g. Prismic.Predicates.at('my.blog_post.title', 'Some Title'),, the API responds with a 400 error in which the error message

[function at(..)] unexpected field 'my.blog_post.title' on line:1 col:48 in query '[[:d = at(document.type, &quot;blog_post&quot;)][:d = at(my.blog_post.title, &quot;&quot;)]]''

[[:d = at(document.type, &quot;blog_post&quot;)][:d = at(my.blog_post.title, &quot;&quot;)]]'

Is returned to me. This occurs when running any sort of predicate on a custom field, including the at and any queries, with or without the proceeding document.type query.

I can't see anything that's wrong with my syntax as I've copied examples directly from the docs, here is the full code I'm running for context:

const Prismic = require("prismic-javascript");

const getArticle = async function() {
  try {
    const api = await Prismic.getApi("https://xxx.prismic.io/api/v2");
    const result = await api.query([
      Prismic.Predicates.at("document.type", "blog_post"),
      Prismic.Predicates.at('my.blog_post.title', 'Some Title'),
    ], {
      orderings: "[my.blog_post.date desc]",
      fetchLinks: "author.name",
    });

    console.log(JSON.stringify(result, null, 2));

  } catch (e) {
    console.warn(e);
  }
}
getArticle();

Any help is greatly appreciated.

API title field returning arrays?

I'm new to Prismic and looking to implement it where I work. I'm currently making a request to the API using the getByUID method and am receiving some data back no problem. I'm a little confused by the structure of the data i'm getting back however.

Currently i'm using getByUID to retrieve a page content type in which the slug is the UID. The page also has a Title field with some text to use for the page title in there.

What I expected to be returned from the API for the title field is a string but instead I received an array that looks like so:

[
spans: [],
text: 'Home',
type: 'heading1'
]

i'm using the Prismic with React on the front end so even after destructuring my props (which are populated with what data I received from the Prismic API), I still have to insert something like {page_title[0].text} in my JSX as opposed to just {page_title}.

Is this how Prismic is intended to send data back or could it be that i've missed something?

Queries keep timing out

Hey there,

For some reason and quite often our calls to the API fail with a ETIMEDOUT. The application runs on a Azure Web App using node-iis. Depending on the resource, a lot of concurrent queries can occur, as we are trying to fetch nested references (imagine a navigation) or a slice that references a different resource.

Here are some examples of the errors:

(node:5748) UnhandledPromiseRejectionWarning: FetchError: request to https://xxx.cdn.prismic.io/api/v2 failed, reason: connect ETIMEDOUT 54.192.27.125:443
    at ClientRequest.<anonymous> (D:\home\site\wwwroot\node_modules\node-fetch\index.js:133:11)
    at emitOne (events.js:116:13)
    at ClientRequest.emit (events.js:211:7)
    at TLSSocket.socketErrorListener (_http_client.js:387:9)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

or

(node:5748) UnhandledPromiseRejectionWarning: FetchError: request to https://xxx.cdn.prismic.io/api/v2/documents/search?page=1&pageSize=100&lang=it-ch&ref=....&q=%5B%5Bany(document.type%2C%20%5B%22default_page%22%2C%22empty_page%22%2C%22communities_page%22%2C%22home_page%22%2C%22ranking_page%22%2C%22sponsors_page%22%5D)%5D%5D failed, reason: connect ETIMEDOUT 54.192.27.125:443
    at ClientRequest.<anonymous> (D:\home\site\wwwroot\node_modules\node-fetch\index.js:133:11)
    at emitOne (events.js:116:13)
    at ClientRequest.emit (events.js:211:7)
    at TLSSocket.socketErrorListener (_http_client.js:387:9)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

These are just some examples and I wasn't able to reproduce them. For every incoming request we initialize the API and reuse that API throughout the request.

Do you have any ideas what could cause this problem? Is there something I can do? Is it possible to set a keep alive agent for the requests to your API?

I am interested to see what you guys think. I haven't found any way yet, to resolve this issue.

Typings : Allow string[] for QueryOptions in ResolvedApi.d.ts

When fetching multiple Fields QueryOptions type definition throws error as it does not allow string[], only string | number

From the Documentation: Fetch Link - Fetch multiple fields

api.getByUID('recipe', 'chocolate-chip-cookies',
    { fetchLinks : ['author.name', 'author.picture'] }
).then(function(document) {
    var author = document.data.author_link;
    // the variable author now works like a top-level document
    var authorName = author.data.name;
    console.log(authorName);
});

throws error

Argument of type '{ 'fetchLinks': string[]; }' is not assignable to parameter of type 'QueryOptions'.

Typedefinitions in ResolvedApi.d.ts should be:

export interface QueryOptions {
    [key: string]: string[] | string | number;
}

Preview document on node server not working

When making api calls (using prismic-javacript) on our node server we always get the latest published document instead of the draft one. If I log the cookies I can see that we have the "io.prismic.preview" cookie on the node side just before the api call is made but the returned document is always the published one. Running the same code on the client works fine however.

Target _blank

There is a easy way to add target=_blank to the links ?

Error /preview handler on Next.js static export

Following stack trace emitted...
TypeError: Only absolute URLs are supported
at getNodeRequestOptions (C:\Users\Napo\Documents\Github\yafo\node_modules\cross-fetch\node_modules\node-fetch\lib\index.js:1284:9)
at C:\Users\Napo\Documents\Github\yafo\node_modules\cross-fetch\node_modules\node-fetch\lib\index.js:1370:19
at new Promise ()
at Object.fetch (C:\Users\Napo\Documents\Github\yafo\node_modules\cross-fetch\node_modules\node-fetch\lib\index.js:1367:9)
at Object.fetch (C:\Users\Napo\Documents\Github\yafo\node_modules\cross-fetch\dist\node-ponyfill.js:10:20)
at C:\Users\Napo\Documents\Github\yafo\node_modules\prismic-javascript\dist\prismic-javascript.min.js:1:14816
at u (C:\Users\Napo\Documents\Github\yafo\node_modules\prismic-javascript\dist\prismic-javascript.min.js:1:15142)
at t.request (C:\Users\Napo\Documents\Github\yafo\node_modules\prismic-javascript\dist\prismic-javascript.min.js:1:15319)
at C:\Users\Napo\Documents\Github\yafo\node_modules\prismic-javascript\dist\prismic-javascript.min.js:1:18238
at new Promise ()

Ordering when use Predicates.any

I was wondering if we could sort the results of several types :
Prismic.Predicates.any('document.type', ['page', 'serie'], { orderings : '[my.serie.rank]' })

I don't get any results with this...

Thanks 🙏

node_modules/prismic-javascript/d.ts/ApiSearchResponse.d.ts(9,14): error TS2304: Cannot find name 'Document'.

Errors like these are blocking TS compilation:


node_modules/prismic-javascript/d.ts/ApiSearchResponse.d.ts(9,14): error TS2304: Cannot find name 'Document'.

9     results: Document[];
               ~~~~~~~~


node_modules/prismic-javascript/d.ts/ResolvedApi.d.ts(88,88): error TS2304: Cannot find name 'Document'.

88     queryFirst(q: string | string[], optionsOrCallback: QueryOptions | RequestCallback<Document>, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                          ~~~~~~~~


node_modules/prismic-javascript/d.ts/ResolvedApi.d.ts(88,120): error TS2304: Cannot find name 'Document'.

88     queryFirst(q: string | string[], optionsOrCallback: QueryOptions | RequestCallback<Document>, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                                                          ~~~~~~~~


node_modules/prismic-javascript/d.ts/ResolvedApi.d.ts(88,140): error TS2304: Cannot find name 'Document'.

88     queryFirst(q: string | string[], optionsOrCallback: QueryOptions | RequestCallback<Document>, cb?: RequestCallback<Document>): Promise<Document>;
                 ~~~~~~~~


node_modules/prismic-javascript/d.ts/ResolvedApi.d.ts(92,75): error TS2304: Cannot find name 'Document'.

92     getByID(id: string, maybeOptions?: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                             ~~~~~~~~


node_modules/prismic-javascript/d.ts/ResolvedApi.d.ts(92,95): error TS2304: Cannot find name 'Document'.

92     getByID(id: string, maybeOptions?: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                                 ~~~~~~~~


node_modules/prismic-javascript/d.ts/ResolvedApi.d.ts(100,91): error TS2304: Cannot find name 'Document'.

100     getByUID(type: string, uid: string, maybeOptions?: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                              ~~~~~~~~


node_modules/prismic-javascript/d.ts/ResolvedApi.d.ts(100,111): error TS2304: Cannot find name 'Document'.

100     getByUID(type: string, uid: string, maybeOptions?: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                                                  ~~~~~~~~


node_modules/prismic-javascript/d.ts/ResolvedApi.d.ts(104,79): error TS2304: Cannot find name 'Document'.

104     getSingle(type: string, maybeOptions?: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                  ~~~~~~~~


node_modules/prismic-javascript/d.ts/ResolvedApi.d.ts(104,99): error TS2304: Cannot find name 'Document'.

104     getSingle(type: string, maybeOptions?: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                                      ~~~~~~~~


node_modules/prismic-javascript/d.ts/ResolvedApi.d.ts(108,85): error TS2304: Cannot find name 'Document'.

108     getBookmark(bookmark: string, maybeOptions?: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                        ~~~~~~~~


node_modules/prismic-javascript/d.ts/ResolvedApi.d.ts(108,105): error TS2304: Cannot find name 'Document'.

108     getBookmark(bookmark: string, maybeOptions?: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                                            ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(8,88): error TS2304: Cannot find name 'Document'.

8     queryFirst(q: string | string[], optionsOrCallback: QueryOptions | RequestCallback<Document>, cb: RequestCallback<Document>): Promise<Document>;
                                                                                         ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(8,119): error TS2304: Cannot find name 'Document'.

8     queryFirst(q: string | string[], optionsOrCallback: QueryOptions | RequestCallback<Document>, cb: RequestCallback<Document>): Promise<Document>;
                                                                                                                        ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(8,139): error TS2304: Cannot find name 'Document'.

8     queryFirst(q: string | string[], optionsOrCallback: QueryOptions | RequestCallback<Document>, cb: RequestCallback<Document>): Promise<Document>;
               ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(9,68): error TS2304: Cannot find name 'Document'.

9     getByID(id: string, options: QueryOptions, cb: RequestCallback<Document>): Promise<Document>;
                                                                     ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(9,88): error TS2304: Cannot find name 'Document'.

9     getByID(id: string, options: QueryOptions, cb: RequestCallback<Document>): Promise<Document>;
                                                                                         ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(11,84): error TS2304: Cannot find name 'Document'.

11     getByUID(type: string, uid: string, options: QueryOptions, cb: RequestCallback<Document>): Promise<Document>;
                                                                                      ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(11,104): error TS2304: Cannot find name 'Document'.

11     getByUID(type: string, uid: string, options: QueryOptions, cb: RequestCallback<Document>): Promise<Document>;
                                                                                                          ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(12,72): error TS2304: Cannot find name 'Document'.

12     getSingle(type: string, options: QueryOptions, cb: RequestCallback<Document>): Promise<Document>;
                                                                          ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(12,92): error TS2304: Cannot find name 'Document'.

12     getSingle(type: string, options: QueryOptions, cb: RequestCallback<Document>): Promise<Document>;
                                                                                              ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(13,78): error TS2304: Cannot find name 'Document'.

13     getBookmark(bookmark: string, options: QueryOptions, cb: RequestCallback<Document>): Promise<Document>;
                                                                                ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(13,98): error TS2304: Cannot find name 'Document'.

13     getBookmark(bookmark: string, options: QueryOptions, cb: RequestCallback<Document>): Promise<Document>;
                                                                                                    ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(24,88): error TS2304: Cannot find name 'Document'.

24     queryFirst(q: string | string[], optionsOrCallback: QueryOptions | RequestCallback<Document>, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                          ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(24,120): error TS2304: Cannot find name 'Document'.

24     queryFirst(q: string | string[], optionsOrCallback: QueryOptions | RequestCallback<Document>, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                                                          ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(24,140): error TS2304: Cannot find name 'Document'.

24     queryFirst(q: string | string[], optionsOrCallback: QueryOptions | RequestCallback<Document>, cb?: RequestCallback<Document>): Promise<Document>;
                 ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(25,69): error TS2304: Cannot find name 'Document'.

25     getByID(id: string, options: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                       ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(25,89): error TS2304: Cannot find name 'Document'.

25     getByID(id: string, options: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                           ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(27,85): error TS2304: Cannot find name 'Document'.

27     getByUID(type: string, uid: string, options: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                       ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(27,105): error TS2304: Cannot find name 'Document'.

27     getByUID(type: string, uid: string, options: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                                           ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(28,73): error TS2304: Cannot find name 'Document'.

28     getSingle(type: string, options: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                           ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(28,93): error TS2304: Cannot find name 'Document'.

28     getSingle(type: string, options: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                               ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(29,79): error TS2304: Cannot find name 'Document'.

29     getBookmark(bookmark: string, options: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                 ~~~~~~~~


node_modules/prismic-javascript/d.ts/client.d.ts(29,99): error TS2304: Cannot find name 'Document'.

29     getBookmark(bookmark: string, options: QueryOptions, cb?: RequestCallback<Document>): Promise<Document>;
                                                                                                     ```

TSConfig:

{
"compilerOptions": {
"target": "es5",
"outDir": "build",
"moduleResolution": "node",
"module": "commonjs",
"declaration": true,
"importHelpers": true,
"inlineSourceMap": true,
"listFiles": false,
"traceResolution": false,
"pretty": true,
"lib" : [
"es6",
"es2015.promise",
"es2015",
"es2017.object",
"dom"
],
"types" : [
"node"
],
"baseUrl": ".", // required for "paths"
"paths": {
"functions": ["src/index.ts"] // write tests without relative paths
}
},
"include": [
"index.ts"
],
"exclude": [
"node_modules/**"
],
"compileOnSave": false
}

Type error preventing google closure advanced compilation.

There is a type issue that prevents the google closure compiler from knowing that it can't re-write the "Accept" in request.ts. I'm pretty sure it is related to this error, which can be seen by running tsc in the project root.

src/request.ts(43,24): error TS2352: Type '{ headers: { Accept: string; }; }' cannot be converted to type 'NodeRequestInit'.
  Types of property 'headers' are incompatible.
    Type '{ Accept: string; }' is not comparable to type 'Headers | string[][] | undefined'.
      Type '{ Accept: string; }' is not comparable to type 'string[][]'.
        Property 'length' is missing in type '{ Accept: string; }'.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.